您好,欢迎访问一九零五行业门户网

Java 实例 - 状态监测

以下实例演示了如何通过继承 thread 类并使用 currentthread.getname() 方法来监测线程的状态:
/* author by w3cschool.cc main.java */class mythread extends thread{ boolean waiting= true; boolean ready= false; mythread() { } public void run() { string thrdname = thread.currentthread().getname(); system.out.println(thrdname + " starting."); while(waiting) system.out.println("waiting:"+waiting); system.out.println("waiting..."); startwait(); try { thread.sleep(1000); } catch(exception exc) { system.out.println(thrdname + " interrupted."); } system.out.println(thrdname + " terminating."); } synchronized void startwait() { try { while(!ready) wait(); } catch(interruptedexception exc) { system.out.println("wait() interrupted"); } } synchronized void notice() { ready = true; notify(); }}public class main { public static void main(string args[]) throws exception{ mythread thrd = new mythread(); thrd.setname("mythread #1"); showthreadstatus(thrd); thrd.start(); thread.sleep(50); showthreadstatus(thrd); thrd.waiting = false; thread.sleep(50); showthreadstatus(thrd); thrd.notice(); thread.sleep(50); showthreadstatus(thrd); while(thrd.isalive()) system.out.println("alive"); showthreadstatus(thrd); } static void showthreadstatus(thread thrd) { system.out.println(thrd.getname() + "alive:=" + thrd.isalive() + " state:=" + thrd.getstate()); }}
以上代码运行输出结果为:
……alive alivemythread #1 terminating. alive……
以上就是java 实例 - 状态监测的内容。
其它类似信息

推荐信息