⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadpool.java

📁 一个用Java编写的调度线程池内的线程的演示程序.
💻 JAVA
字号:
import java.util.*;
/**-----------------------------------
* <br>功能概述:线程池,调度线程池内的线程
------------------------------------*/
public class ThreadPool{
	private LinkedList tasks = new LinkedList();

	public ThreadPool(int PoolSize){
		for(int i=0;i<PoolSize;i++){
			Thread t = new SingleThread(this);
			t.setDaemon(true);
			t.start();
		}		
	}//ThreadPool()
	
	/**-----------------------------------
	* <br>功能概述:运行线程任务
	------------------------------------*/
	public void run(Runnable task){
		synchronized(tasks){
			tasks.addLast(task);	
			tasks.notify();
		}
	}//run()
	
	/**-----------------------------------
	* <br>功能概述:获得下一个线程任务
	------------------------------------*/
	Runnable getNext(){
		Runnable run = null;
		synchronized(tasks){
			while(tasks.isEmpty()){
				try{
					tasks.wait();
				}
				catch(InterruptedException e){}
			}
			run = (Runnable)tasks.removeFirst();
		}	
		return run;
	}//getNext()
	
	/**-----------------------------------
	* <br>功能概述:显示消息
	------------------------------------*/
	public static void main(String argv[]){
		String message[] = {"A","B","C","D","E"};
		ThreadPool tp = new ThreadPool(message.length/2);
		
		for(int i=0;i<message.length;i++){
			myRunnable runner = new myRunnable(i,message);
			tp.run(runner);
		}
	}//main()
}/** ThreadPool */

/**-----------------------------------
* <br>功能概述:线程池内的单线程
------------------------------------*/
class SingleThread extends Thread{
	private ThreadPool Pool;
	
	public SingleThread(ThreadPool Pool){
		this.Pool = Pool;
	}//SingleThread()
	
	/**-----------------------------------
	* <br>功能概述:线程取得任务之后运行任务,等待下一个作业
	------------------------------------*/
	public void run(){
		while(true){
			Runnable job = Pool.getNext();
			try{
				job.run();
			}
			catch(Exception e){}
		}	
	}//run()
}/** SingleThread */

class myRunnable implements Runnable{
	int messageI;
	String message[];
	public myRunnable(int messageI,String s[]){
		this.messageI = messageI;
		this.message = s;
	}//myRunnable()
	
	public void run(){
		for(int j=0;j<5;j++){
			System.out.println(j +": "+ message[messageI]);
		}
	}//run()
}/** myRunnable */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -