使用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種方式的區別