Java中线程通信协作的最常见的两种方式:
一、syncrhoized加锁的线程的Object类的wait()/notify()/notifyAll()
二、ReentrantLock类加锁的线程的Condition类的await()/signal()/signalAll()
线程间直接的数据交换
wait()/notify()
public class WaitDemo {
private static Object lock = new Object();
private static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
while (flag) {
try {
System.out.println("wait start .......");
lock.wait();
System.out.println("醒来了 .......");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("wait end ....... ");
}
}
}).start();
// 让上面对线程执行一会儿
Thread.sleep(1000);
new Thread(new Runnable() {
@Override
public void run() {
if (flag) {
synchronized (lock) {
if (flag) {
lock.notify();
System.out.println("notify .......");
flag = false;
}
}
}
}
}).start();
}
}
await()/signal()
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " 开始处理任务");
condition.await();
System.out.println(Thread.currentThread().getName() + " 结束处理任务");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " 开始处理任务");
Thread.sleep(2000);
condition.signal();
System.out.println(Thread.currentThread().getName() + " 结束处理任务");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("----");
lock.unlock();
}
}).start();
}
}