常见方式及代码示例
- 调用
Object
类的 wait()
方法
- 当线程调用某个对象的
wait()
方法时,该线程会释放持有的对象锁,进入 WAITING
状态,直到其他线程调用该对象的 notify()
或 notifyAll()
方法将其唤醒。
- 代码示例:
public class WaitNotifyExample {
public static void main(String[] args) {
Object lock = new Object();
Thread thread = new Thread(() -> {
synchronized (lock) {
System.out.println("线程进入同步块,开始等待");
try {
lock.wait();
System.out.println("线程被唤醒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
System.out.println("主线程获取锁,唤醒等待线程");
lock.notify();
}
}
}
- 调用
Thread
类的 join()
方法
- 当一个线程调用另一个线程的
join()
方法时,调用线程会进入 WAITING
状态,直到被调用的线程执行完毕。
- 代码示例:
public class JoinExample {
public static void main(String[] args) {
Thread threadToJoin = new Thread(() -> {
try {
Thread.sleep(3000);
System.out.println("被join的线程执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadToJoin.start();
Thread mainThread = Thread.currentThread();
Thread joinThread = new Thread(() -> {
try {
threadToJoin.join();
System.out.println("等待被join的线程执行完毕,此线程继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
joinThread.start();
}
}
- 调用
LockSupport
类的 park()
方法
LockSupport
类提供了更灵活的线程阻塞和唤醒机制。调用 park()
方法会使当前线程进入 WAITING
状态,直到其他线程调用 unpark(Thread thread)
方法唤醒该线程。
- 代码示例:
import java.util.concurrent.locks.LockSupport;
public class LockSupportExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("线程开始执行,准备进入WAITING状态");
LockSupport.park();
System.out.println("线程被唤醒");
});
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程唤醒子线程");
LockSupport.unpark(thread);
}
}