public class test extends Thread {
//....
//public void run(){
while(flag){
..........
} }}
JDK API:
public void interrupt()中断线程。
如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。
如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。
查了相关资料,都是利用interrupt()和改变flag=false来中断线程,但不能“立即”中止。
interrupt()中断根本不起作用,只在有Thread.sleep(...)进程睡眠的时候interrupt()起作用,实现了线程中断,其他时候调用interrupt()根本没作用,我的程序里没有睡眠,那岂不是要等到该程序段执行一遍后才能中止。请问如何“立即”中止该线程啊?
//....
//public void run(){
while(flag){
..........
} }}
JDK API:
public void interrupt()中断线程。
如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。
如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。
查了相关资料,都是利用interrupt()和改变flag=false来中断线程,但不能“立即”中止。
interrupt()中断根本不起作用,只在有Thread.sleep(...)进程睡眠的时候interrupt()起作用,实现了线程中断,其他时候调用interrupt()根本没作用,我的程序里没有睡眠,那岂不是要等到该程序段执行一遍后才能中止。请问如何“立即”中止该线程啊?
stop()方法不建议使用。
你的意思是说,程序每执行几行就调用一次:
if(!flag)
return ;
???????????????????
public boolean b=true;
public void run()
{
int i=0;
while(b)
{
System.out.println(" "+i++);
}
}
public void shutDown()
{
b=false;
}
public static void main(String[] args) {
MyThread mt=new MyThread();
mt.start();
for (int i = 0; i < 1000; i++) {
System.out.println(" main Thread= "+i);
}
System.out.println("over");
mt.shutDown();
}
}
isInterrupted(),若是被其他的线程中断,则return
MyThread mt=new MyThread();
mt.suspend();刮起线程
mt.resume();恢复线程
你的例子方法run()中执行的代码短,改变b=false就可以,但如果代码很长呢,一直在执行,想中断的话,要执行完1编才能中止。
方法已过时。不建议使用。
isInterrupted()测试线程是否已经中断。线程的中断状态 不受该方法的影响。 既然interrupted();起不到中断的作用,那么isInterrupted()测试一直是false
我用的就是isInterrupted(),判断是否中断,但会出现死循环,
public void stopPlay(){
while(!isInterrupted())
thread.interrupted();
}