问题:两个线程交替打印1A2B3C...26Z
1.LockSupport
使用LockSupport的unpark()唤醒指定线程,park()挂起当前线程,从而达到两个线程交替执行的效果,代码如下:
package com.example.thread.synchronization;
import java.util.concurrent.locks.LockSupport;
public class ThreadSwitchByLockSupport {
private static Integer numberCount = 26;
private static char startLetter = 'A';
private static char endLetter = 'Z';
private static NumberThread numberThread = new NumberThread();
private static LetterThread letterThread = new LetterThread();
private static class NumberThread extends Thread {
@Override
public void run() {
for (int i = 0; i < numberCount; i++) {
System.out.print(i+1);
LockSupport.unpark(letterThread);
LockSupport.park();
}
}
}
private static class LetterThread extends Thread {
@Override
public void run() {
for (char i = startLetter; i <= endLetter; i++) {
LockSupport.park();
System.out.print(i);
LockSupport.unpark(numberThread);
}
}
}
public static void main(String[] args) {
numberThread.start();
letterThread.start();
}
}
2.synchronized wait notify
定义一个两个线程都能访问的共享对象,线程执行时先使用synchronized持有该共享对象的锁,持有锁才能往下执行。通过该对象的notify()方法通知等待持有该对象锁的线程继续执行,并使用该对象的wait()方法让当前线程进入等待队列。这次就可以实现两个线程交替执行的效果,代码如下:
package com.example.thread.synchronization;
import lombok.SneakyThrows;
import java.util.concurrent.CountDownLatch;
public class ThreadSwitchBySynchronized {
private static Integer numberCount = 26;
private static char startLetter = 'A';
private static char endLetter = 'Z';
/**
* 定义共享对象,通过synchronized(object)获取共享对象的锁信息来阻塞线程执行
*/
private static Object object = new Object();
/**
* 使用countDownLatch.await()阻塞某一线程执行
* 使用countDownLatch.countDown()打开阻塞
* synchronized无法保证线程的执行顺序,加入CountDownLatch用于保证线程的先后执行顺序
*/
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static class NumberThread extends Thread {
@SneakyThrows
@Override
public void run() {
synchronized (object) {
countDownLatch.countDown();
for (int i = 0; i < numberCount; i++) {
System.out.print(i + 1);
object.notify();
object.wait();
}
//循环结束需要唤醒其他等待的线程执行,保证其他线程的正确退出
object.notify();
}
}
}
private static class LetterThread extends Thread {
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
for (char i = startLetter; i <= endLetter; i++) {
System.out.print(i);
try {
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//循环结束需要唤醒其他等待的线程执行,保证其他线程的正确退出
object.notify();
}
}
}
public static void main(String[] args) {
NumberThread numberThread= new NumberThread();
LetterThread letterThread = new LetterThread();
letterThread.start();
numberThread.start();
}
}
3.Lock Condition
定义一个ReentrantLock对象,并创建不同的Condition对象,使用signal()方法唤醒指定Condition队列中的等待线程,使用await()方法让当前线程进入指定的Condition队列中等待。从而保证可以唤醒指定Condition队列种的线程,达到线程交替执行的效果,代码如下:
package com.example.thread.synchronization;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadSwitchByLockCondition {
private static Integer numberCount = 26;
private static char startLetter = 'A';
private static char endLetter = 'Z';
private static ReentrantLock reentrantLock = new ReentrantLock();
/**
* 定义数字输出等待队列
*/
private static Condition conditionNumber = reentrantLock.newCondition();
/**
* 定义字母输出等待队列
*/
private static Condition conditionLetter = reentrantLock.newCondition();
/**
* 使用countDownLatch.await()阻塞某一线程执行
* 使用countDownLatch.countDown()打开阻塞
* ReentrantLock无法保证线程的执行顺序,加入CountDownLatch保证线程的先后执行顺序
*/
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static class NumberThread extends Thread {
@Override
public void run() {
try {
//相当于synchronized
reentrantLock.lock();
countDownLatch.countDown();
for (int i = 0; i < numberCount; i++) {
System.out.print(i + 1);
//相当于notify(),区别是唤醒指定等待队列中的线程
conditionLetter.signal();
//相当于wait(),区别是让当前线程进入指定的队列中等待
conditionNumber.await();
}
//相当于notify()
conditionLetter.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
private static class LetterThread extends Thread {
@Override
public void run() {
try {
countDownLatch.await();
//相当于synchronized
reentrantLock.lock();
for (char i = startLetter; i <= endLetter; i++) {
System.out.print(i);
//相当于notify(),区别是唤醒指定等待队列中的线程
conditionNumber.signal();
//相当于wait(),区别是让当前线程进入指定的队列中等待
conditionLetter.await();
}
//相当于notify()
conditionNumber.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
public static void main(String[] args) {
NumberThread numberThread = new NumberThread();
LetterThread letterThread = new LetterThread();
numberThread.start();
letterThread.start();
}
}
4.TransferQueue
TransferQueue是一种阻塞队列。当生产者使用transfer()方法发送消息给消费者时,线程被阻塞,直到消息被消费者从TransferQueue中取走;当消费者使用take()方法获取消息时,线程也会被阻塞,直到生产者将消息放入TransferQueue中。利用该特性可以实现两个线程的交替执行,代码如下:
package com.example.thread.synchronization;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
public class ThreadSwitchByTransferQueue {
public static void main(String[] args) {
Integer count = 26;
Integer startNumber = 1;
char startLetter = 'A';
// 阻塞队列,队列中只允许有一个数据,
// transfer方法会等待队列中的数据被取走后执行,take方法会等待队列中放入数据后执行
TransferQueue transferQueue = new LinkedTransferQueue();
Thread numberThread = new Thread(() -> {
for (int i = 0; i < count; i++) {
try {
//阻塞等待获取transferQueue中的内容,并输出
System.out.print(transferQueue.take());
//将下一个需要输出的字母放入队列中,阻塞等待字母输出线程take
transferQueue.transfer((char) (startLetter + i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread letterThread = new Thread(() -> {
for (int i = 0; i < count; i++) {
try {
//将下一个需要输出的数字放入队列中,阻塞等待数字输出线程take
transferQueue.transfer(startNumber + i);
//阻塞等待获取transferQueue中的内容,并输出
System.out.print(transferQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
numberThread.start();
letterThread.start();
}
}