使用Object
package study;
public class Test {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
Thread t1 = new Thread(() -> {
System.out.println("进入线程t1");
synchronized (lock) {
System.out.println("线程t1准备进入等待状态");
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("线程t1撤出了");
});
t1.start();
Thread.sleep(1000);
System.out.println("主线程休眠完毕,准备唤醒t1线程");
synchronized (lock) {
lock.notify();
}
}
}
使用Condition
package study;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Test1 {
static ReentrantLock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
lock.lock();
System.out.println("线程t1开始执行");
try {
try {
System.out.println("线程t1在condition上等待");
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
System.out.println("线程t1执行完毕");
});
t1.start();
System.out.println("主线程执行中");
try {
lock.lock();
System.out.println("主线程准备唤醒t1线程");
condition.signal();
} finally {
lock.unlock();
}
}
}
使用lockSupport
package study;
import java.util.concurrent.locks.LockSupport;
public class Test2 {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("线程t1开始执行");
System.out.println("准备使用lockSupport让t1线程等待");
LockSupport.park();
System.out.println("线程t1结束等待,执行完毕");
});
t1.start();
System.out.println("主线程准备睡眠2秒");
Thread.sleep(2000);
System.out.println("主线程睡眠完毕,准备唤醒t1线程");
LockSupport.unpark(t1);
}
}
3种方式的区别
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/77d71052a8f1c0d663f98b3888c992fa.png)