自定义线程池需要什么
需要哪些类
MyTask
@Data
public class MyTask implements Runnable{private int id;MyTask(int id) {this.id = id;}@Overridepublic void run() {String name = Thread.currentThread().getName();System.out.println("线程" + name + "开始执行任务" + id);try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("线程" + name + "完成任务" + id);}
}
MyWorker
public class MyWorker extends Thread{private String name;private List<Runnable> tasks;MyWorker(String name, List<Runnable> tasks) {this.name = name;this.tasks = tasks;}@Overridepublic void run() {while (true) {Runnable task = null;synchronized (tasks) {while (tasks.isEmpty()) {try {tasks.wait();} catch (InterruptedException e) {e.printStackTrace();}}task = tasks.remove(0);}System.out.println("线程" + name + "开始执行任务");task.run();System.out.println("线程" + name + "完成任务");}}
}