JAvaスレッド停止の方法
1128 ワード
1.flagを設定し、デッドサイクルでflagがfalseであるかどうかを検出する
2.interruptメソッド
2.interruptメソッド
public static Object lock=new Object();
public static void main(String[] args) {
Thread thread=new Thread(){
public void run() {
synchronized (lock) {
try {
System.out.println("1");
lock.wait();// ,
System.out.println("2");
} catch (InterruptedException e) {
System.out.println(" ");
e.printStackTrace();
}
}
};
};
thread.start();
thread.interrupt();
wait,sleep,join状態にあるスレッドのうち、interruptメソッドによって中断されるため、スレッドの実行が停止します. Thread thread=new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(System.currentTimeMillis());
}
System.err.println("interrupt");
}
});
thread.start();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
thread.interrupt();
Running状態のスレッドは直接中断されて終了し、異常は放出されません.