关于java 线程的停止同时用 interrupt 和 join 的作用

 

/**

 * @FileName: ThreadTest.java

 * @Description:

 * @Author : xingchong

 * @CreateTime: Sep 22, 2018 12:01:01 PM

 * @Copyright: 超火影游 Copyright (c) 2017

 * @Version: 1.0

 */

public class ThreadTest implements Runnable {

 

private boolean stop = false;

 

private Thread thread;

 

private int flag;

 

public ThreadTest(){

this.thread = new Thread(this, ThreadTest.class.getSimpleName());

this.flag = 0;

}

 

private String getName(){

return "["+Thread.currentThread().getName()+"] ";

}

 

/*

* (non-Javadoc)

* 

* @see java.lang.Runnable#run()

*/

@Override

public void run() {

while(!stop){

System.out.println(this.getName() +", i am running..."+ this.flag++);

if(this.flag > 30){

break;

}

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(this.getName()+", i am end...");

}

 

public synchronized void start(){

this.thread.start();

}

 

public synchronized void stop(){

System.out.println(this.getName() +", stop the thread...");

this.stop = true;

this.thread.interrupt();//马上中断 thread 正在进行的 sleep 等操作,而让停止操作立即执行

//若没有上面interrupt()方法,会导致 thread 发呆在 sleep ,担耽时机

 

try {

this.thread.join();//为了现在马上转入 thread 线程,以触发this.stop引起的停止操作,而不用再让main线程抢 CPU,担耽时机

} catch (InterruptedException e) {

e.printStackTrace();

}

 

//若没有上面的 join()方法,会导致以下代码在停止前执行

for (int i = 0; i < 3; i++) {

System.out.println(this.getName() +"in stop ...");

}

}

 

public static void main(String[] args) {

ThreadTest threadTest = new ThreadTest();

threadTest.start();

 

for (int i = 0; i < 3; i++) {

System.out.println(threadTest.getName()+", main...." + i);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

 

threadTest.stop();

System.out.println(threadTest.getName()+", main is end...");

}

 

}

猜你喜欢

转载自www.cnblogs.com/xingchong/p/9689964.html