背景
曾几何时,机器支持的线程数目是一个8位的记录的。这就意味着最多支持的线程数目是255个。如果我们需要同时的执行流上千怎么办。
虽然现在有多核多线程,如果一个CPU已经满足需要你又想减少多线程开发的成本代价。
场景
此模式的核心是一个在单线程中执行的循环。循环通过等待需要的处理的任务。
实例
Task.java
public interface Task { public void execute(); }
PrintTask.java
public class PrintTask implements Task { @Override public void execute() { System.out.println(System.nanoTime()); } }
ExecuteEngineer.java
import java.util.Stack; public class ExecuteEngineer { private Stack<Task> pendingTasks; private static ExecuteEngineer engineer = new ExecuteEngineer(); private ExecuteEngineer(){ pendingTasks = new Stack<Task>(); } public static ExecuteEngineer getEngineer(){ return engineer; } public void run(){ while(true){ Task task = null; if(!pendingTasks.isEmpty()){ task = pendingTasks.pop(); } if(task == null){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }else{ task.execute(); } } } public void postTask(Task task){ pendingTasks.push(task); } }
Test.java
public class Test { public static void main(String args[]){ new Thread(){ @Override public void run() { ExecuteEngineer.getEngineer().run(); } }.start(); new Thread(){ @Override public void run() { while (true){ try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } ExecuteEngineer.getEngineer().postTask(new PrintTask()); } } }.start(); } }
时间: 2024-10-24 22:39:05