一个最简单的线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import  java.util.concurrent.ExecutorService;
import  java.util.concurrent.Executors;
 
/**
  * 一个最简单的线程池,这个模型很简单,但是很有用
  *
  * @author leizhimin 2014/8/22 20:21
  */
public  class  Test3 {
     private  static  final  ExecutorService threadPool = Executors.newFixedThreadPool( 1 );
 
     public  static  void  main(String[] args)  throws  InterruptedException {
 
         for  ( int  i =  0 ; i <  10000 ; i++) {
             final  int  finalI = i;
             Runnable r =  new  Runnable() {
                 @Override
                 public  void  run() {
                     System.out.println(String.valueOf(finalI)+ ":" +System.currentTimeMillis());
                 }
             };
             threadPool.submit(r);
             Thread.currentThread().sleep(300L);
         }
 
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
0 : 1409187082455
1 : 1409187082755
2 : 1409187083055
3 : 1409187083355
4 : 1409187083655
5 : 1409187083955
6 : 1409187084255
7 : 1409187084555
8 : 1409187084855
9 : 1409187085155
10 : 1409187085455
11 : 1409187085755
。。。



本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/1545968,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单线程池代码示例,其中包括线程池初始化、任务添加、线程执行任务和线程池销毁等功能: ```c++ #include <iostream> #include <thread> #include <vector> #include <queue> #include <mutex> #include <condition_variable> class ThreadPool { public: ThreadPool(size_t numThreads) : stop(false) { for (size_t i = 0; i < numThreads; ++i) { workers.emplace_back( [this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) { return; } task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } } ); } } template<class F> void enqueue(F&& f) { { std::unique_lock<std::mutex> lock(queue_mutex); tasks.emplace(std::forward<F>(f)); } condition.notify_one(); } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (std::thread& worker : workers) { worker.join(); } } private: std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; ``` 在上述代码中,构造函数初始化了线程池,并创建了指定数量的线程。enqueue()函数用于向线程池中添加任务。当调用enqueue()时,任务会被放置在任务队列中,并通过std::condition_variable通知线程池中的线程执行任务。线程池的析构函数会等待所有线程完成任务后销毁线程池
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值