博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个简单的工作者线程实现
阅读量:4109 次
发布时间:2019-05-25

本文共 2499 字,大约阅读时间需要 8 分钟。

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."); }}

转载地址:http://tjlsi.baihongyu.com/

你可能感兴趣的文章
application/x-www-form-urlencoded、multipart/form-data、text/plain
查看>>
关于Content-Length
查看>>
WebRequest post读取源码
查看>>
使用TcpClient可避免HttpWebRequest的常见错误
查看>>
EntityFramework 学习之一 —— 模型概述与环境搭建 .
查看>>
C# 发HTTP请求
查看>>
初试visual studio2012的新型数据库LocalDB
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Generate Parentheses--生成匹配括号(重)
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>