Description:
1 uses the advanced first out idea of the queue
2) to add a thread at execution
3 to get the threads from the queue in the Threadqueue
/** * * @Project Javademos * @Package com.java.thread * @author Chenlin * @version 1.0 * @Date 2 011/June 12/public class Workqueue {private int threadcounts;//thread pool size private threadqueue[] threads;//using arrays to implement lines Pool private LinkedList queue;//task queue public workqueue (int threadcounts) {this.threadcounts = Threadcounts
;
This.threads = new Threadqueue[threadcounts];
This.queue = new LinkedList ();
for (int i = 0; i < threadcounts i++) {threads[i] = new Threadqueue ();
Threads[i].start ()//Start all worker threads} public void execute (Runnable r) {synchronized (queue) {
Queue.addlast (R);
Queue.notify ();
} private class Threadqueue extends thread {//Worker thread class @Override public void run () {
Runnable R; while (true) {synchronized (queue) {//While (Queue.isempty ())
{try {queue.wait ();
catch (Interruptedexception e) {e.printstacktrace ();
} r = (Runnable) Queue.removefirst ()//when there is a task, remove the task}
R.run ();
}}/** * Calling inner class in static method must be static/static class MyTask implements Runnable {//task interface
public void Run () {String name = Thread.CurrentThread (). GetName ();
try {thread.sleep (100);//Simulate Time of task execution} catch (Interruptedexception e) {}
SYSTEM.OUT.PRINTLN (name + "executed OK"); } public static void Main (string[] args) {workqueue Wq = new Workqueue (10);//10 Worker threads MyTask
r[] = new mytask[20];//20 tasks for (int i = 0; i < i++) {R[i] = new MyTask (); Wq.execute (R[i]); }
}
}
Run Result:
Thread-2 executed OK
Thread-6 executed OK
Thread-1 executed OK
Thread-5 executed OK
thre Ad-9 executed OK
Thread-7 executed OK
Thread-4 executed OK
Thread-8 executed OK
Thread-3 executed OK br> Thread-0 executed OK
Thread-2 executed OK
Thread-5 executed OK
Thread-1 executed OK
Thread-9 Execu Ted OK
Thread-7 executed OK
Thread-6 executed OK
Thread-4 executed OK
Thread-8 executed OK
Thread -3 executed OK
Thread-0 executed OK