java线程间通信sync
时间: 2023-11-21 13:51:14 浏览: 43
Java中的线程间通信可以使用synchronized关键字来实现。具体来说,可以使用wait()方法使线程进入等待状态,直到其他线程调用notify()或notifyAll()方法来唤醒它们。在使用wait()和notify()时,必须先获得对象的锁,因此通常会将它们放在synchronized块中。
例如,以下代码演示了两个线程之间的通信:
```
public class ThreadCommunication {
public static void main(String[] args) {
final Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1 is waiting");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 is notified");
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 is running");
lock.notify();
}
});
t1.start();
t2.start();
}
}
```
输出结果为:
```
Thread 1 is waiting
Thread 2 is running
Thread 1 is notified
```