执行线程ExecuteThread类
public class ExecuteThread extends Thread {
boolean runningFlag = false;
private Runnable callBack;
public void setCallBack(Runnable callBack) {
this.callBack = callBack;
}
public synchronized void setRunningFlag(boolean runningFlag) {
this.runningFlag = runningFlag;
if (runningFlag) {
this.notify();
}
}
@Override
public synchronized void run() {
while (true) {
while (!runningFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
callBack.run();
setRunningFlag(false);
}
}
}
线程调度ThreadPoolExecutor类
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ThreadPoolExecutor {
List<ExecuteThread> threads;
public ThreadPoolExecutor(int n) {
threads = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < n; i++) {
ExecuteThread executeThread = new ExecuteThread();
threads.add(executeThread);
executeThread.start();
}
}
public void execute(Runnable callBack) {
int i = 0;
while (true) {
for (; i < threads.size(); i++) {
ExecuteThread executeThread = threads.get(i);
if (!executeThread.runningFlag) {
executeThread.setCallBack(callBack);
executeThread.setRunningFlag(true);
break;
}
}
if (i == threads.size()) {
System.out.println("没有资源,请稍后再访问");
}
else {
System.out.println("我在停止");
return;
}
}
}
}
测试类Test
public class PoolTest {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5);
for (int i = 0; i < 5; i++) {
int finalI = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPoolExecutor.execute(() -> System.out.println("任务"+ finalI));
}
System.exit(0);
}
}