前言
废话不多直接上代码,我用的jdk是11,所以如果代码跟贵兄的环境不兼容欢迎留言。
代码
import java.util.concurrent.atomic.AtomicBoolean;
public class ThreadTest {
//测试线程休眠和唤醒
@Test
public void testThread() throws InterruptedException {
MyThread t1 = new MyThread();
//执行线程
t1.start();
System.out.println("main thread to sleep");
Thread.sleep(3000);
System.out.println("main thread t1 notify");
//唤醒线程
t1.keep();
Thread.sleep(3000);
System.out.println("test end");
}
/**
* 测试的线程
*/
private static class MyThread extends Thread {
private AtomicBoolean wait = new AtomicBoolean(false);
@Override
public void run() {
System.out.println("t1 run start");
//休眠
this.hold();
System.out.println("t1 run end");
}
/**
* 休眠线程
*/
public void hold(){
synchronized (wait){
if(this.wait.get()){
return;
}
this.wait.set(true);
try {
this.wait.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 唤醒线程
*/
public void keep(){
synchronized (wait){
if(!this.wait.get()){
return;
}
this.wait.set(false);
this.wait.notify();
}
}
}
}