一个简单的工作者线程实现

0. 一个简单的工作者线程实现
  • 我认为在涉及多线程/并发编程时,如果没有丰富的经验,则极易出错。所以应当优先使用 JDK 中提供的并发编程类。
  • 必须留心共享变量的竞态条件。可能一不小心便会造成死锁。多思考,多分析。且代码尽量简洁,控制共享变量的操作/使用范围。
1. 代码如下:
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.");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值