多线程协调模板
Posted huanstephen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程协调模板相关的知识,希望对你有一定的参考价值。
在多线程进行相互协调是个头疼的事,今天写个多线程协调操作模板,以后只要套用这个模板就好了
public abstract class Order implements Runnable { protected boolean open = true; protected ReentrantLock lock; protected Condition condition; protected static int STATUS = 0; public Order(ReentrantLock lock, Condition condition) { this.lock = lock; this.condition = condition; } public void run() { while (!Thread.interrupted() && this.open) { this.doSomething(); } } private void doSomething() { this.lock.lock(); try { while (this.getStatus() != STATUS) { try { this.condition.await(); if (this.getStatus() != STATUS) { this.doSomething(); return ; } } catch (InterruptedException e) { this.open = false; return ; } } this.content(); if (this.stop()) { return ; } STATUS = this.changeStatus(); this.condition.signalAll(); } finally { this.lock.unlock(); } } public abstract int getStatus(); public abstract void content(); public abstract int changeStatus(); public boolean stop() { return false; } }
下面我们来测试一下,有这么一个需求,有三个线程,线程A输出三行OperateA,线程B输出两行OperateB,线程C输出一行OperateC,然后按照这种顺序循环三次。
测试示例:
public class ThreadOrderTest { public static class OperateA extends Order { public OperateA(ReentrantLock lock, Condition condition) { super(lock, condition); } @Override public int getStatus() { return 0; } @Override public void content() { for (int i = 0; i < 3; i ++) { System.out.println("OperateA"); } } @Override public int changeStatus() { return 1; } } public static class OperateB extends Order { public OperateB(ReentrantLock lock, Condition condition) { super(lock, condition); } @Override public int getStatus() { return 1; } @Override public void content() { for (int i = 0; i < 2; i ++) { System.out.println("OperateB"); } } @Override public int changeStatus() { return 2; } } public static class OperateC extends Order { private ExecutorService exec; private int max; public OperateC(ReentrantLock lock, Condition condition, ExecutorService exec, int max) { super(lock, condition); this.exec = exec; this.max = max; } @Override public int getStatus() { return 2; } @Override public void content() { System.out.println("OperateC"); } @Override public int changeStatus() { return 0; } public boolean stop() { if (0 == --this.max) { this.open = false; this.exec.shutdownNow(); return true; } return false; } } public static void main(String[] args) { ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new OperateB(lock, condition)); exec.execute(new OperateC(lock, condition, exec, 3)); exec.execute(new OperateA(lock, condition)); } }
输出:
OperateA
OperateA
OperateA
OperateB
OperateB
OperateC
OperateA
OperateA
OperateA
OperateB
OperateB
OperateC
OperateA
OperateA
OperateA
OperateB
OperateB
OperateC
以上是关于多线程协调模板的主要内容,如果未能解决你的问题,请参考以下文章