从java文档中得出:interrupt是中断线程,为此我做了个试验public class Interrupt {
public static void main(String[] args) {
Runnable it=new InterruptTest();
Thread thread=new Thread(it);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
class InterruptTest implements Runnable {
@Override
public void run() {
int i=0;
while(true){
System.out.println(i++);
}
}}按理说2秒应该不打印才对,可是它一直打印个没完?
求高手
public static void main(String[] args) {
Runnable it=new InterruptTest();
Thread thread=new Thread(it);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
class InterruptTest implements Runnable {
@Override
public void run() {
int i=0;
while(true){
System.out.println(i++);
}
}}按理说2秒应该不打印才对,可是它一直打印个没完?
求高手
private boolean stop = false;
int count=0;
@Override
public void run() {
while (!stop){
try {
Thread.sleep(2000);
count++;
stop = true;
System.out.println(count);
System.out.println("线程终止");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public static void main(String[] asrgs) {
MyThread t = new MyThread();
t.start();
}
}
多个线程的时候才可以用其他线程来判断另一个线程是否中断
写错了,应该改成 while(!Thread.currentThread().isInterrupted()),少了个感叹号,嘿嘿