public void run() { while(runFlag && !interrupted) { .... } } Two Methods 1)set flag 2)use Thread.interrupe()
public void run() { while(runFlag && !this.isInterrupted()) { .... } } Two Methods 1)set flag 2)use Thread.interrupt()
Thread.interrupt()目的是不是就是为了制造一个异常,好让线程退出?
Thread.interrupt()目的是不是就是为了制造一个异常,好让线程退出? -------------------------------------- Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread. 当你的线程睡着了的时候,别人调用了interrupt(),那么就抛出异常,否则,不会抛出。所以,你需要在while循环中使用两个条件!interrupted() && more work todo。睡着的时候被中断,通过InterruptedException异常退出,工作的时候被中断则通过主动判断中断标志来退出。
Thread B
{
private boolean runFlag = true; public void run()
{
while(runFlag)
{
....
}
}
public void setRunFlag(boolean flag)
{
this.runFlag = flag;
}
}当Thread A 发现时间不符合条件的时候,就调用Thread B的setRunFlag(boolean flag)方法。这样Thread B就会停止。当然,你在启动Thread B的时候,让它保留一个引用在Thread A里面,这样就可以调用Thread B的方法了
Thread A
{
private Thread b = null;
public void register(Thread argThread)
{
this.b = argThread;
} public void run()
{
while(true)
{
if(时间不符合条件)
b.setRunFlag(false);
}
}
}
O'relliy的JAVA Thread 有详细介绍
{
while(runFlag && !interrupted)
{
....
}
}
Two Methods
1)set flag
2)use Thread.interrupe()
{
while(runFlag && !this.isInterrupted())
{
....
}
}
Two Methods
1)set flag
2)use Thread.interrupt()
--------------------------------------
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.
当你的线程睡着了的时候,别人调用了interrupt(),那么就抛出异常,否则,不会抛出。所以,你需要在while循环中使用两个条件!interrupted() && more work todo。睡着的时候被中断,通过InterruptedException异常退出,工作的时候被中断则通过主动判断中断标志来退出。
一是作为判断循环的条件要是同步读取,或声明为易变类型的。
二是要interrupt一下
想想java的ide工具, 他们调试的时候能随时中止线程...它们是怎么做到的?
目前为止我还是只能用stop完成上面的要求.唉....