码迷,mamicode.com
首页 > 编程语言 > 详细

初识多线程

时间:2015-12-23 10:40:32      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

 1 package executors_test;
 2 
 3 import java.util.concurrent.ArrayBlockingQueue;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 import java.util.concurrent.RejectedExecutionHandler;
 7 import java.util.concurrent.ScheduledExecutorService;
 8 import java.util.concurrent.ScheduledThreadPoolExecutor;
 9 import java.util.concurrent.ThreadPoolExecutor;
10 import java.util.concurrent.TimeUnit;
11 
12 public class Executors_test {
13 
14     public static void main(String[] args) {
15 
16         
17         scheduledThreadPoolExecutorTest();
18     }
19 
20 
21 
22     /**
23      * ScheduledThreadPoolExecutor类可用于定时启动线程,以及周期启动线程
24      */
25     public static void scheduledThreadPoolExecutorTest() {
26         ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(2, new MyRejectedExecutionHandler());
27         pool.scheduleAtFixedRate(new MyThread(5), 10000,1000,TimeUnit.MILLISECONDS);
28     }
29 
30 
31 
32     /**
33      * ThreadPoolExecutor类实现的多线程
34      */
35     public static void threadPoolExecutorTest() {
36         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 2,TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(4),new MyRejectedExecutionHandler());
37         for (int i = 0; i < 100; i++) {
38             threadPoolExecutor.execute(new MyThread(i));
39         }
40     }
41 
42     
43     
44     /**
45      * Executors工厂类实现的多线程,
46      */
47     public static void newFixedThreadPoolTest(){
48         ExecutorService executors = Executors.newFixedThreadPool(2);
49         for (int i = 0; i < 10; i++) {
50             executors.execute(new MyThread(i));
51         }
52     };
53     /**
54      * Executors工厂类实现的多线程,可用于定时启动线程,以及周期启动线程
55      */
56     public static void newScheduledThreadPoolTest(){
57         ScheduledExecutorService executors = Executors.newScheduledThreadPool(2);
58         executors.scheduleAtFixedRate(new MyThread(5), 10000,1000,TimeUnit.MILLISECONDS);
59     }
60     
61     
62     static class MyThread implements Runnable {
63         int id;
64 
65         public MyThread(int id) {
66             this.id = id;
67         }
68         @Override
69         public void run() {
70             System.out.println(Thread.currentThread().getName()+"........"+id);
71         }
72     }
73     
74     static class MyRejectedExecutionHandler implements RejectedExecutionHandler{
75         @Override
76         public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
77             System.out.println(r.toString()+"");
78         }
79     }
80 }

 

初识多线程

标签:

原文地址:http://www.cnblogs.com/freezone/p/5068880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!