1. 线程池
View Code
package com; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class MutiThread extends Thread { private static int MaxTask = 3; private static int currTask = 0; private static ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors .newFixedThreadPool(MaxTask); private static String[][] task = { { "a", "a" }, { "b", "b" }, { "c", "c" }, { "d", "d" }, { "e", "e" }, { "f", "f" }, { "g", "g" }, { "h", "h" }, { "i", "i" }, { "g", "g" }, { "k", "k" }, { "l", "l" }, { "m", "m" }, { "n", "n" }, { "o", "o" }, { "u", "u" }, { "p", "p" }, { "r", "r" }, { "s", "s" }, { "t", "t" }, { "u", "u" }, { "v", "v" }, { "w", "w" }, { "x", "x" }, { "y", "y" }, { "z", "z" } }; public synchronized static void addTask() { if (currTask >= task.length) { pool.shutdown(); return; } TaskThread tt = new TaskThread(); tt.setTname(task[currTask][0]); pool.execute(tt); currTask++; } @Override public void run() { for (int i = 0; i < MaxTask + 3; i++) { addTask(); } } public static void main(String[] args) { new MutiThread().start(); } }
2. 任务对象
View Code
package com; import java.util.Random; public class TaskThread extends Thread { private int count = 3; private String tname; private static final Random r = new Random(System.currentTimeMillis()); public void setTname(String tname) { this.tname = tname; } @Override public void run() { while (count > 0) { try { int i = sleepTime(); System.out.println(getName() + ":" + tname + ", sleep " + i + "s"); Thread.sleep(i * 1000); } catch (InterruptedException e) { e.printStackTrace(); } count--; } MutiThread.addTask(); } public synchronized int sleepTime() { return (r.nextInt(10) + 1); } public static void main(String[] args) { new TaskThread().start(); } }