本文共 2499 字,大约阅读时间需要 8 分钟。
import java.util.concurrent.atomic.AtomicInteger;public class Worker extends Thread { private static final AtomicInteger counter = new AtomicInteger(1); // 记录当前正在执行的 task, null 值则表示 worker 处于空闲状态(即 进入wait() 等待派发任务 task) private volatile Runnable task; private static final String NAME_PREFIX = "worker-"; private final String workerName; private boolean isInterrupted = false; private volatile boolean isRunning = false; private volatile boolean isStarted = false; private boolean isDestroyed = false; public Worker(String name) { this.workerName = NAME_PREFIX + counter.getAndIncrement() + (name == null ? "" : "-" + name); } public Worker() { this(null); } public Worker(String name, Runnable task) { this(name); this.task = task; } public boolean doTask(Runnable task) { if (task == null) { throw new IllegalArgumentException("task must not be null."); } if (!isStarted && !isDestroyed) { this.start(); }else if (isDestroyed) { throw new IllegalStateException("this worker was destroyed."); } // 尝试减少锁的获取次数 if (this.task != null) { return false; } return compareAndUpdate(null, task); } /** 比较然后更新 */ private synchronized boolean compareAndUpdate(Runnable old, Runnable update) { if (this.task == old) { this.task = update; if (this.task != null) { // 通知 worker 继续工作 this.notify(); } return true; } return false; } public boolean isRunning() { return this.isRunning; } public boolean isStarted() { return this.isStarted; } public String getWorkerName() { return workerName; } @Override public void run() { this.isStarted = true; while(!isInterrupted) { this.isRunning = true; Runnable currentTask = task; if (currentTask != null) { currentTask.run(); compareAndUpdate(currentTask, null); }else { synchronized (this) { try { // 避免死锁 if (this.task != null) { continue; }else { this.isRunning = false; wait(); } } catch (InterruptedException ignore) { isInterrupted = true; // 再次设置自身的中断状态 this.interrupt(); } } } } this.isStarted = false; this.isDestroyed = true; } public void exit() { this.isDestroyed = true; this.isStarted = false; this.interrupt(); System.out.println(getWorkerName() + " exited."); }}
转载地址:http://tjlsi.baihongyu.com/