1.可以通过共享变量来通信
2.wait notify
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Object lock = new Object();
Thread child = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("子线程等待");
lock.wait();
System.out.println("子线程被唤醒");
} catch (InterruptedException e) {
}
}
});
child.start();
Thread.sleep(2000);
synchronized (lock) {
lock.notify();
}3.join 父线程等待子线程
1
2
3
4
5
6
7Thread t = new Thread(() -> {
System.out.println("子线程执行");
});
t.start();
t.join(); // 父线程等待子线程
System.out.println("父线程继续");4.Future / Callable(推荐)
1
2
3
4
5
6ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Integer> future = pool.submit(() -> {
return 100;
});
Integer result = future.get(); // 父线程获取结果
System.out.println(result);5.BlockingQueue 生成者消费者
1
2
3
4
5
6
7
8
9
10BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
new Thread(() -> {
try {
queue.put("hello");
} catch (Exception e) {}
}).start();
String msg = queue.take();
System.out.println(msg);
为什么wait()必须在synchronized 里调用,而sleep()不需要?
wait()必须在synchronized中调用,是因为它依赖对象的监视器锁(monitor),并且会释放该锁;
而sleep()只是让线程休眠,不涉及锁机制
wait() 是 Object 的方法,用于线程之间的通信,它会释放当前对象的监视器锁并进入等待队列,因此必须在 synchronized 块中调用,否则线程没有持有该对象的锁,JVM 会抛出 IllegalMonitorStateException。
而 sleep() 是 Thread 的方法,仅仅是让当前线程暂停执行一段时间,不涉及锁的释放,因此不需要在 synchronized 中调用