Java 实现自己的简单线程池

package com.zzf.concurrence.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ZzfThreadPool {
	// 线程池的思路:
	// 工作线程数--》拿CPU内核数;
	// 任务总数;
	// blockingqueue
	// execute (runnabel) put
	// stopwork

	private static int WORKCOUNT =Runtime.getRuntime().availableProcessors();
	private static int TASKCOUNT =100;

	private static final int QUEUE_COUNUT = 100;

	private BlockingQueue<Runnable> queue;

	private WordThread[] threads;
	
	public ZzfThreadPool() {
		this(WORKCOUNT,TASKCOUNT);
	}

	public ZzfThreadPool(int workCount, int taskCount) {
		workCount =workCount<=0?WORKCOUNT:workCount;
		taskCount =taskCount<=0?TASKCOUNT:taskCount;
		init(workCount, taskCount);

	}

	private void init(int workCount, int taskCount) {
		threads = new WordThread[workCount];
		queue = new ArrayBlockingQueue<>(QUEUE_COUNUT);
		for (int i = 0; i < threads.length; i++) {
			threads[i] =new WordThread();
			threads[i].start();
			
		}
		
		

	}
	
	public void execute(Runnable n) {
		
		try {
			queue.put(n);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void destroy() {
		
		//任务终止
		for (int i = 0; i < threads.length; i++) {
			threads[i].stopWork();
			threads[i] =null;
		}
		queue.clear();
		
		//清除队列
		
		
		
	}

	private class WordThread extends Thread {

		@Override
		public void run() {
			while (!isInterrupted()) {
				try {
					if(queue==null) {
						
						System.out.println("queue为空:"+Thread.currentThread().getName());
						return;
					}
					Runnable r = queue.take();
//					System.out.println("准备执行:"+Thread.currentThread().getName());
					
					if(r!=null)r.run();
					
				} catch (InterruptedException e) {
					e.printStackTrace();
					// TODO: 处理 exception
				}

			}

		}

		public void stopWork() {

			interrupt();

		}

	}

}

 

测试类:

 

package com.zzf.concurrence.threadpool;

import java.util.Random;

import com.zzf.concurrence.SleepTools;

public class ZzfThreadPoolTest {

	public static void main(String[] args) {

		// 10个线程,看他怎么执行
		ZzfThreadPool pool = new ZzfThreadPool();
		for (int i = 0; i < 10; i++) {
			MyWork myWork = new MyWork("run-name:" + i);
			pool.execute(myWork);
		}

		SleepTools.second(15);

		System.out.println(":main 执行完成。。。");
		
//		pool.destroy();

	}

	private static class MyWork implements Runnable {

		private String name;
		public MyWork(String name) {
			this.name = name;
		}

		@Override
		public void run() {

			Random random = new Random();
			SleepTools.ms(1000 + random.nextInt(500));
			System.out.println(name + ":执行完成。。。");

		}

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值