This commit is contained in:
坏黑
2018-05-07 14:43:57 +08:00
parent 7181c487f9
commit 6f34cbc2e0
152 changed files with 9256 additions and 9003 deletions

View File

@@ -3,82 +3,80 @@ package me.skymc.taboolib.thread;
import java.util.LinkedList;
public class ThreadUtils {
private static PoolWorker[] threads;
private static final LinkedList<Runnable> queue = new LinkedList<>();
/**
* 构造方法
*
* @param number 线程数量
*/
public ThreadUtils(int number) {
threads = new PoolWorker[number];
private static PoolWorker[] threads;
private static final LinkedList<Runnable> queue = new LinkedList<>();
for (int i = 0; i < number; i++) {
threads[i] = new PoolWorker();
threads[i].setName("TabooLib WorkThread - " + i);
threads[i].start();
}
}
/**
* 停止工作
*
*/
public void stop() {
for (PoolWorker p : threads) {
p.stop();
}
}
/**
* 构造方法
*
* @param number 线程数量
*/
public ThreadUtils(int number) {
threads = new PoolWorker[number];
/**
* 添加任务
*
* @param r
*/
public void execute(Runnable r) {
// 线程锁
synchronized (queue) {
// 添加任务
queue.addLast(r);
// 开始任务
queue.notify();
}
}
for (int i = 0; i < number; i++) {
threads[i] = new PoolWorker();
threads[i].setName("TabooLib WorkThread - " + i);
threads[i].start();
}
}
private class PoolWorker extends Thread {
@Override
public void run() {
Runnable runnable;
while (true) {
// 线程锁
synchronized (queue) {
// 如果任务为空
while (queue.isEmpty()) {
// 等待任务
try {
queue.wait();
} catch (InterruptedException ignored) {
}
}
// 获取任务
runnable = queue.removeFirst();
}
// 运行任务
try {
runnable.run();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 停止工作
*/
public void stop() {
for (PoolWorker p : threads) {
p.stop();
}
}
/**
* 添加任务
*
* @param r
*/
public void execute(Runnable r) {
// 线程锁
synchronized (queue) {
// 添加任务
queue.addLast(r);
// 开始任务
queue.notify();
}
}
private class PoolWorker extends Thread {
@Override
public void run() {
Runnable runnable;
while (true) {
// 线程锁
synchronized (queue) {
// 如果任务为空
while (queue.isEmpty()) {
// 等待任务
try {
queue.wait();
} catch (InterruptedException ignored) {
}
}
// 获取任务
runnable = queue.removeFirst();
}
// 运行任务
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}