线程池

来源:互联网 发布:软件开发费用明细 编辑:程序博客网 时间:2024/06/06 08:51
package com.ygl;
public class ThreadPoolRunnable implements Runnable{

@Override
public void run() {

for(int i=1;i<=10;i++){
System.out.println(Thread.currentThread().getName()+" is looping of  "+i);
}
}

}

//*****************************************************

package com.ygl;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
     public static void main(String[] args) {
    // ThreadPoolRunnable  threadPoolRunnable=new ThreadPoolRunnable();
    ExecutorService  threadPool= Executors.newFixedThreadPool(3);//创建3个线程
    for(int i=1;i<=10;i++){
    //System.out.println("Task: "+i+"===============");
    threadPool.execute(new ThreadPoolRunnable());
    }  
        System.out.println("all task commit");
        threadPool.shutdown();
     
     }
}

//*************************************************************

package com.ygl;


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


public class ThreadPoolTest {
     public static void main(String[] args) {
    // ThreadPoolRunnable  threadPoolRunnable=new ThreadPoolRunnable();
    ExecutorService  threadPool= Executors.newCachedThreadPool();//根据任务动态创建线程
    for(int i=1;i<=10;i++){
    //System.out.println("Task: "+i+"===============");
    threadPool.execute(new ThreadPoolRunnable());
    }
   
        System.out.println("all task commit");
        threadPool.shutdown();
     
     
     }
}

//************************************************************

package com.ygl;


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


public class ThreadPoolTest {
     public static void main(String[] args) {
    // ThreadPoolRunnable  threadPoolRunnable=new ThreadPoolRunnable();
    ExecutorService  threadPool= Executors.newCachedThreadPool();//创建3个线程
    for(int i=1;i<=10;i++){
    //System.out.println("Task: "+i+"===============");
    threadPool.execute(new ThreadPoolRunnable());
    }
   
        System.out.println("all task commit");
        threadPool.shutdown();
      
        //定时任务调度
        Executors.newScheduledThreadPool(3).schedule(new ThreadPoolRunnable(),10,TimeUnit.SECONDS);
    Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new ThreadPoolRunnable(),10,2,TimeUnit.SECONDS);//10s后炸,每隔2s触发一次
     }
     
     
     
}

0 0