1. 程式人生 > >Java newFixedThreadPool監控當前執行緒的執行狀況

Java newFixedThreadPool監控當前執行緒的執行狀況

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThreadPool {

	private ExecutorService exe;
	private static final int POOL_SIZE = 4;
	
	public MyThreadPool() {
        exe = Executors.newFixedThreadPool(POOL_SIZE);
    }
	
	public void doTask() {
        int i = 0;
        while (i < 50) {
            exe.execute(new MyThread(i, exe));
            i++;
        }
    }
	
	class MyThread implements Runnable
    {
        int id;
        ExecutorService exe;
        MyThread(int id, ExecutorService exe) {
        	this.exe = exe;
            this.id = id;
        }
        public void run() {
        	System.out.println(id + "start");
        	try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	
        	System.out.println(id + "pass 5 second");
        	System.out.println("exe info:" + exe.toString());
        	try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	
            System.out.println(id + "end");
        }
    }
	
	public static void main(String[] args) {
        new MyThreadPool().doTask();
    }
}
MyThreadPool為執行緒池管理類

MyThread為實際需要執行的執行緒類

執行log如下(一小部分):

  1. <span style="font-size:18px;">1start  
  2. 2start  
  3. 3start  
  4. 0start  
  5. 2pass 5 second  
  6. exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]  
  7. 0pass 5 second  
  8. exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]  
  9. 3pass 5 second  
  10. exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]  
  11. 1pass 5 second  
  12. exe info:java.util.concurrent.ThreadPoolExecutor@39890510[Running, pool size = 4, active threads = 4, queued tasks = 46, completed tasks = 0]  
  13. 2end  
  14. 4start  
  15. 0end  
  16. 5start  
  17. 3end  
  18. 6start  
  19. 1end  
  20. 7start  
  21. </span>  

可以看到當前在執行的執行緒只有前4個,佇列中有46個任務在等待

只要有一個執行緒結束立即就會執行佇列中的下一個執行緒