假设有3个线程,依次打印A、B、C,按顺序循环打印100次。
这个其实是线程通信,如果只是按顺序执行,用只有一个线程的线程池,依次提交线程任务就行,但是这里还不是每个线程只执行一次,需要循环重复打印。
这里有两种处理方式,一种是搞个全局int变量,对线程数取模,得到0~2,再转ASCII码。一种是3个线程按照创建时的顺序严格执行。
第一种思路写法:
这里只用到了原生的阻塞唤醒方法,线程竞争获取锁,确保同时只有一个线程累加countIndex和打印,3个线程的执行顺序就不是创建的顺序,而是随机的。文章来源:https://www.toymoban.com/news/detail-759701.html
public class ThreeThreadPrintOrderlyBySync {
private static final Object LOCK = new Object();
private static volatile int countIndex = 0;
private static final int MAX = 100;
private static final int WORKER_COUNT = 3;
public static void main(String[] args) {
Thread thread1 = new Thread(new Worker(0));
Thread thread2 = new Thread(new Worker(1));
Thread thread3 = new Thread(new Worker(2));
thread1.start();
thread2.start();
thread3.start();
}
public static class Worker implements Runnable {
private final int index;
public Worker(int index) {
this.index = index;
}
@Override
public void run() {
while (countIndex < MAX) {
synchronized (LOCK) {
try {
if (countIndex % WORKER_COUNT != index) {
LOCK.wait();
}
if (countIndex <= MAX) {
System.out.printf(String.valueOf((char) (65 + countIndex % WORKER_COUNT)));
}
countIndex++;
LOCK.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
第二种处理方式:
通过线程序号控制ReentrantLock中Condition的阻塞唤醒文章来源地址https://www.toymoban.com/news/detail-759701.html
public class ThreeThreadPrint {
private static final int WORKER_COUNT = 3;
private static final ReentrantLock LOCK = new ReentrantLock();
private static int countIndex = 0;
public static void main(String[] args) {
List<Condition> conditions = new ArrayList<>();
for (int i = 0; i < WORKER_COUNT; i++) {
Condition condition = LOCK.newCondition();
conditions.add(condition);
Thread thread = new Worker(i, conditions);
thread.start();
}
}
public static class Worker extends Thread {
private int index;
private List<Condition> conditions;
public Worker(int index, List<Condition> conditions) {
super("Thread" + index);
this.index = index;
this.conditions = conditions;
}
@Override
public void run() {
while (true) {
LOCK.lock();
try {
if (countIndex % WORKER_COUNT != index) {
conditions.get(index).await();
}
if (countIndex > 100) {
conditions.get((index + 1) % conditions.size()).signal();
return;
}
System.out.printf(String.valueOf((char) (65 + countIndex % 3)));
countIndex++;
conditions.get((index + 1) % conditions.size()).signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
LOCK.unlock();
}
}
}
}
}
到了这里,关于线程按顺序循环执行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!