多线程交互
在Java中,可以使用synchronized
关键字或者java.util.concurrent
包中的
ReentrantLock来实现多线程交替打印。
方式一:synchronized
public class ThreadJH_Synchronized {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(ThreadJH_Synchronized::threadTwo);
executorService.submit(ThreadJH_Synchronized::threadOne);
executorService.shutdown();
}
private static Integer count = 0;
private static Object lockObject = new Object();
private static void threadOne() {
while (count < 10) {
synchronized (lockObject) {
if (count >= 10) {
return;
}
Util.mySleep(100);
Util.printfLog("thread 1,current count=" + count);
count++;
//用于唤醒一个在此对象监视器上等待的线程。
lockObject.notify();
try {
//判断ccount 小于等于满足条件才进入等待。如果不增加判断线程无法结束线程,会死锁
if (count < 10) {
//让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
lockObject.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
private static void threadTwo() {
while (count < 10) {
synchronized (lockObject) {
if (count >= 10) {
return;
}
Util.mySleep(100);
Util.printfLog("thread 2,current count=" + count);
count++;
//用于唤醒一个在此对象监视器上等待的线程。
lockObject.notify();
try {
if (count < 10) {
//让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
lockObject.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
方式二:ReentrantLock
public class ThreadJH_ReentrantLock {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(ThreadJH_ReentrantLock::threadOne);
executorService.submit(ThreadJH_ReentrantLock::threadTwo);
executorService.shutdown();
}
private static Integer count = 0;
private static ReentrantLock lock = new ReentrantLock();
//定义了两个`Condition`对象`condition1`和`condition2`,它们用于线程间的协调/通信。
private static final Condition condition1 = lock.newCondition();
private static final Condition condition2 = lock.newCondition();
private static void threadOne() {
while (count < 10) {
lock.lock();
if (count >= 10) {
return;
}
try {
Util.mySleep(100);
Util.printfLog("thread 1,current count=" + count);
count++;
//唤醒等待:
// 如果有任何线程正在等待与 `condition2` 关联的 `Lock` 上的 `condition2.await();`,则调用 `signal()` 方法会选择其中一个线程(如果有多个线程在等待)并通知它可以继续执行
condition2.signal();
//判断ccount 小于满足条件才进入等待。如果不增加判断线程无法结束线程,会死锁
if (count < 10) {
//当前线程释放锁,等待
// 调用`await()`方法的线程会释放与`Condition`关联的`Lock`,允许其他线程获得这个锁并执行它们的任务。
condition1.await();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
private static void threadTwo() {
while (count < 10) {
lock.lock();
if (count >= 10) {
return;
}
try {
Util.mySleep(100);
Util.printfLog("thread 2,current count=" + count);
count++;
//唤醒等待:
condition1.signal();
if (count < 10) {
//当前线程释放锁,等待
condition2.await();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
}
参考: