java线程全面讲解

线程的使用在开发中可以说是无处不在,场景特别多;当然也是很难控制的。当然你要玩的好,也是很好的。

简单的讲,线程本质上不能加快程序的运行(当然多cpu的机器例外了),只不过优化时间调度而已,在我们看来整体上快了点;但搞不好由于在线程间的切换消耗太多精力导致整个程序运行效率降低也很有可能,所以为何多线程的情况下就要不断尝试,找到最优线程数,也就是这个道理了。不过多线程运行有一个明显的好处啦(不管程序是变快了还是变慢了),那就是对于用户来说,减少对用户的等待时间,不然单线程跑任务,用户可能面对的就是一个时刻“卡死”的程序了(特别在界面上的处理)。

下面就用代码来描述线程的一些基本知识,这里描述的比较多,但基本能覆盖工作当中的应用了。

[java]  view plain  copy
  1. package com.wxshi.thread;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Random;  
  7. import java.util.Set;  
  8. import java.util.Timer;  
  9. import java.util.TimerTask;  
  10. import java.util.concurrent.Callable;  
  11. import java.util.concurrent.CompletionService;  
  12. import java.util.concurrent.ConcurrentHashMap;  
  13. import java.util.concurrent.CopyOnWriteArrayList;  
  14. import java.util.concurrent.CopyOnWriteArraySet;  
  15. import java.util.concurrent.CountDownLatch;  
  16. import java.util.concurrent.CyclicBarrier;  
  17. import java.util.concurrent.Exchanger;  
  18. import java.util.concurrent.ExecutionException;  
  19. import java.util.concurrent.ExecutorCompletionService;  
  20. import java.util.concurrent.ExecutorService;  
  21. import java.util.concurrent.Executors;  
  22. import java.util.concurrent.Future;  
  23. import java.util.concurrent.Semaphore;  
  24. import java.util.concurrent.atomic.AtomicInteger;  
  25. import java.util.concurrent.locks.Condition;  
  26. import java.util.concurrent.locks.Lock;  
  27. import java.util.concurrent.locks.ReadWriteLock;  
  28. import java.util.concurrent.locks.ReentrantLock;  
  29. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  30.   
  31. /** 
  32.  * 线程的介绍,这里做个笔记 下面会从简单到高级介绍线程 
  33.  * 
  34.  * @author wxshi 
  35.  * 
  36.  */  
  37. public class TraditionalThread {  
  38.   
  39.     // -----------演示线程的创建方法,及内部方法体的调用原理-----------  
  40.   
  41.     /** 
  42.      * 第一种创建线程 :public class ChildThread extends Thread(){} 
  43.      * 通过Thread子类覆盖Thread的run()方法,以实现线程运行自己的业务 
  44.      */  
  45.     public void thread_init1() {  
  46.         Thread thread = new Thread() {  
  47.             @Override  
  48.             public void run() {  
  49.                 while (true) {  
  50.                     try {  
  51.                         Thread.sleep(1000);  
  52.                         System.out.println(Thread.currentThread().getName());  
  53.                     } catch (InterruptedException e) {  
  54.                         e.printStackTrace();  
  55.                     }  
  56.                 }  
  57.             }  
  58.         };  
  59.         thread.start();  
  60.     }  
  61.   
  62.     /** 
  63.      * 第二种方法创建线程:Thread thread = new Thread(Runnable runnable); 
  64.      * 将线程运行的run()方法宿主到Runnable对象,以实现面向对象思想。 
  65.      * Thread在构造的时候会将Runnable内的run()方法作为自己的目标,在启动时会运行 
  66.      * 
  67.      */  
  68.     public void thread_init2() {  
  69.         Thread thread = new Thread(new Runnable() {  
  70.   
  71.             @Override  
  72.             public void run() {  
  73.                 try {  
  74.                     Thread.sleep(1000);  
  75.                     System.out.println(Thread.currentThread().getName());  
  76.                 } catch (InterruptedException e) {  
  77.                     e.printStackTrace();  
  78.                 }  
  79.             }  
  80.         });  
  81.   
  82.         thread.start();  
  83.     }  
  84.   
  85.     /** 
  86.      * 注意:ruannable()宿主里面的run方法会赋给Thread(父类),所以上面两种方法同时出现时 
  87.      * 只会调用子类线程实现方式的run方法,因为覆盖了Thread(父类)的run方法,管你怎么传,都会被覆盖。 
  88.      * */  
  89.   
  90.     // -----------演示线程定时任务,quartz的使用-----------  
  91.   
  92.     /** 
  93.      * 线程之定时任务 具体定时需求更多的可以调用quartz时间api进行配置定时,这里不做多介绍 
  94.      * 
  95.      **/  
  96.     public void thread_traditionTimerTask() {  
  97.         Timer task = new Timer();  
  98.   
  99.         // 10s以后启动定时任务,只执行一次  
  100.         task.schedule(new TimerTask() {  
  101.             @Override  
  102.             public void run() {  
  103.                 System.out.println("task start");  
  104.             }  
  105.         }, 10000);  
  106.   
  107.         // 10s以后启动定时任务,以后每5s执行一次  
  108.         task.schedule(new TimerTask() {  
  109.             @Override  
  110.             public void run() {  
  111.                 System.out.println("task start");  
  112.             }  
  113.         }, 100005000);  
  114.     }  
  115.   
  116.     // -----------演示线程互斥,锁的使用-----------  
  117.   
  118.     OutPrint out = new OutPrint();  
  119.   
  120.     /** 
  121.      * 线程间的互斥,下面的方法仅仅代表在被多线程调用时,会实现线程间的互斥 多个线程使用同一把锁会实现方法的同步,若使用的不是同一把锁,就不能实现同步 
  122.      * 
  123.      */  
  124.     public void thread_sync1() {  
  125.   
  126.         // 10个线程线程调用打印方法,保证每个线程都打印完整的字符串  
  127.         for (int i = 0; i < 10; i++) {  
  128.             new Thread(new Runnable() {  
  129.                 @Override  
  130.                 public void run() {  
  131.                     try {  
  132.                         Thread.sleep(500);  
  133.                         out.print1("shiwenxue");  
  134.                     } catch (Exception e) {  
  135.                         e.printStackTrace();  
  136.                     }  
  137.                 }  
  138.             }).start();  
  139.         }  
  140.     }  
  141.   
  142.     /** 
  143.      * 内部类。保证程序完整打印str字符串 
  144.      */  
  145.     static class OutPrint {  
  146.   
  147.         String lock = ""// 这里定义只当锁,没有其他作用。  
  148.   
  149.         /** 
  150.          * 方法体 只锁住部分代码段,该保护的代码被保护,这部分代码只能一次被一个线程共享 此处用的锁是该对象 
  151.          * 适用于一个方法部分代码共享,部分代码受保护 
  152.          * 
  153.          * @param str 
  154.          */  
  155.         public void print1(String str) {  
  156.   
  157.             // 锁住方法主体,使得没车只供一个县线程调用  
  158.             // this可以是一个公共变量,代表锁栓,不一定是当前对象,这里用当前对象当锁栓  
  159.             // synchronized (lock) lock在方法体外定义的一个对象,也可以充当锁栓。  
  160.   
  161.             synchronized (this) {  
  162.                 for (char c : str.toCharArray()) {  
  163.                     System.out.print(c);  
  164.                 }  
  165.                 System.out.println();  
  166.             }  
  167.         }  
  168.   
  169.         /** 
  170.          * 锁住整个方法,该保护的代码被保护,这部分代码只能一次被一个线程共享 此处用的锁是该对象 
  171.          * 注意:由于此方法的锁也是该对象,与print1是同一个锁,因此这两个方法本身也互斥(锁在谁手上,谁就有权利调用) 如果,print1 
  172.          * 用的锁是lock(定义的string),而print2用的是this,则不互斥 
  173.          * 
  174.          * @param str 
  175.          */  
  176.         public synchronized void print2(String str) {  
  177.             for (char c : str.toCharArray()) {  
  178.                 System.out.println(c);  
  179.             }  
  180.         }  
  181.   
  182.         /** 
  183.          * 若添加静态方法,并且想与print1,print2两个方法同步,所有方法必须使用OutPrint.class对象作为锁 
  184.          * 因为静态方法属于类本身,而类本身字节码(OutPrint.class)就是静态方法所属对象。 
  185.          * 
  186.          * @param str 
  187.          */  
  188.         public static synchronized void print3(String str) {  
  189.             for (char c : str.toCharArray()) {  
  190.                 System.out.println(c);  
  191.             }  
  192.         }  
  193.     }  
  194.   
  195.     /** 
  196.      * java5中提供了另外一种锁Lock,下面简单说明一下(这种锁更加面向对象) 
  197.      */  
  198.     class output2 {  
  199.   
  200.         // 定义锁  
  201.         Lock lock = new ReentrantLock();  
  202.   
  203.         /** 
  204.          * 下面的方法会上锁 
  205.          * 
  206.          * @param str 
  207.          */  
  208.         public void print1(String str) {  
  209.             lock.lock(); // 给核心代码段上锁  
  210.             try {  
  211.                 for (char c : str.toCharArray()) {  
  212.                     System.out.println(c);  
  213.                 }  
  214.             } finally { // 若核心代码段执行异常了 ,当然要释放锁  
  215.                 lock.unlock();// 释放锁,  
  216.             }  
  217.         }  
  218.     }  
  219.   
  220.     /** 
  221.      * 以一个自定义的缓存器来演示读写锁: 
  222.      * 读锁:允许多个线程同时读取,但不能写; 
  223.      * 写锁:只允许当前线程写,不允许其他操作 
  224.      */  
  225.     class MyCache {  
  226.   
  227.         // 缓存map  
  228.         private Map<String, Object> myCache = new HashMap<String, Object>();  
  229.   
  230.         // 读写锁  
  231.         private ReadWriteLock rwLock = new ReentrantReadWriteLock();  
  232.   
  233.         // 获取数据,这里允许多人同时获取,但在写时只能一个人操作  
  234.         public Object getData(String key) {  
  235.             rwLock.readLock().lock(); // 上读锁,允许多人读,但此时不允许写  
  236.             Object value = null;  
  237.             try {  
  238.                 value = myCache.get(key);  
  239.                 // 若缓存中没有数据,就从数据库或其他地方获取,并加入缓存  
  240.                 // 但此时释放读锁,加写锁,保证只有一个人能操作且只操作一次  
  241.                 if (null == value) {  
  242.                     rwLock.readLock().unlock();// 释放读锁  
  243.                     rwLock.writeLock().lock();// 加写锁  
  244.                     try {  
  245.                         if (null == value) { // 这里再判断一次是防止其他线程也走到这一步再次获取  
  246.                             value = ""// 从其他地方获取  
  247.                         }  
  248.                     } finally {  
  249.                         rwLock.writeLock().unlock();// 获取了数据之后,释放写锁,再加读锁  
  250.                     }  
  251.                 }  
  252.             } finally {  
  253.                 rwLock.readLock().unlock();// 释放读锁  
  254.             }  
  255.             return value;  
  256.         }  
  257.     }  
  258.   
  259.     // -----------演示线程间通信-----------  
  260.   
  261.     /** 
  262.      * 线程间通信,这里以一个示例演示:子线程运行10次,主线程运行20次,交替运行,各自执行100次 
  263.      */  
  264.     public void thread_communication() {  
  265.   
  266.         final Business business = new Business();  
  267.   
  268.         // 定义子线程  
  269.         new Thread(new Runnable() {  
  270.             @Override  
  271.             public void run() {  
  272.                 for (int i = 0; i < 100; i++) {  
  273.                     business.subBusiness(); // 子线程业务  
  274.                 }  
  275.   
  276.             }  
  277.         }).start();  
  278.   
  279.         // 方法体本身作为主线程  
  280.         for (int i = 0; i < 100; i++) {  
  281.             business.mainBusiness(); // 主线程业务  
  282.         }  
  283.     }  
  284.   
  285.     /** 
  286.      * 内部类,里面包含主线程与子线程业务实现, 这样容易管理任务,实现互斥与通信 
  287.      * 
  288.      * @author wxshi 
  289.      * 
  290.      */  
  291.     class Business {  
  292.   
  293.         // 唤醒标志,第一次执行为子线程,保证交替执行  
  294.         private boolean isTimeForSub = true;  
  295.   
  296.         /** 
  297.          * 子线程业务,运行10次 加锁保证每次要么子线程运行,要么主线程运行 
  298.          */  
  299.         public synchronized void subBusiness() {  
  300.   
  301.             // 若为false,则子线程等待  
  302.             while (!isTimeForSub) {  
  303.                 try {  
  304.                     this.wait();// 当前线程等待  
  305.                 } catch (InterruptedException e) {  
  306.                     e.printStackTrace();  
  307.                 }  
  308.             }  
  309.   
  310.             // 若为true,则执行代码  
  311.             for (int i = 0; i < 10; i++) {  
  312.                 System.out.println("sub loop times: " + i);  
  313.             }  
  314.   
  315.             isTimeForSub = false// 执行完10次,唤醒标志为false  
  316.             this.notify(); // 唤醒其他线程(此处为主线程)  
  317.         }  
  318.   
  319.         /** 
  320.          * 主线程业务,运行20次 
  321.          */  
  322.         public synchronized void mainBusiness() {  
  323.             // 若为true,则主线程等待  
  324.             while (isTimeForSub) {  
  325.                 try {  
  326.                     this.wait();// 当前线程等待  
  327.                 } catch (InterruptedException e) {  
  328.                     e.printStackTrace();  
  329.                 }  
  330.             }  
  331.   
  332.             // 若为false,则执行代码  
  333.             for (int i = 0; i < 20; i++) {  
  334.                 System.out.println("main loop times: " + i);  
  335.             }  
  336.   
  337.             isTimeForSub = true// 执行完20次,唤醒标志为true  
  338.             this.notify(); // 唤醒其他线程  
  339.         }  
  340.     }  
  341.   
  342.     /** 
  343.      * 内部类,里面包含主线程与子线程业务实现, 这样容易管理任务,实现互斥与通信 
  344.      * 此类的演示完全与上面Business一样,只不过这里使用Condition来实现线程间的通信,取代传统的 wait() 和 notify(); 
  345.      * 注意:Condition与Lock成对使用 
  346.      * 
  347.      * @author wxshi 
  348.      * 
  349.      */  
  350.     class Business2 {  
  351.   
  352.         // 唤醒标志,第一次执行为子线程,保证交替执行  
  353.         private boolean isTimeForSub = true;  
  354.   
  355.         // 定义锁  
  356.         Lock lock = new ReentrantLock();  
  357.         // 获取Condition  
  358.         Condition condition = lock.newCondition();  
  359.   
  360.         /** 
  361.          * 子线程业务,运行10次 加锁保证每次要么子线程运行,要么主线程运行 
  362.          */  
  363.         public void subBusiness() {  
  364.   
  365.             // 若为false,则子线程等待  
  366.             while (!isTimeForSub) {  
  367.                 try {  
  368.                     // this.wait();// 当前线程等待  
  369.                     condition.await(); // 此处用await();代表等待  
  370.                 } catch (InterruptedException e) {  
  371.                     e.printStackTrace();  
  372.                 }  
  373.             }  
  374.   
  375.             // 若为true,则执行代码  
  376.             for (int i = 0; i < 10; i++) {  
  377.                 System.out.println("loop times: " + i);  
  378.             }  
  379.   
  380.             isTimeForSub = false// 执行完10次,唤醒标志为false  
  381.             // this.notify(); // 唤醒其他线程(此处为主线程)  
  382.             condition.signal(); // 唤醒其他线程(此处为主线程)  
  383.         }  
  384.   
  385.         /** 
  386.          * 主线程业务,运行20次 
  387.          */  
  388.         public synchronized void mainBusiness() {  
  389.             // 若为true,则主线程等待  
  390.             while (isTimeForSub) {  
  391.                 try {  
  392.                     // this.wait();// 当前线程等待  
  393.                     condition.await(); // 此处用await();代表等待  
  394.                 } catch (InterruptedException e) {  
  395.                     e.printStackTrace();  
  396.                 }  
  397.             }  
  398.   
  399.             // 若为false,则执行代码  
  400.             for (int i = 0; i < 20; i++) {  
  401.                 System.out.println("loop times: " + i);  
  402.             }  
  403.   
  404.             isTimeForSub = true// 执行完20次,唤醒标志为true  
  405.             // this.notify(); // 唤醒其他线程  
  406.             condition.signal(); // 唤醒其他线程(此处为主线程)  
  407.         }  
  408.     }  
  409.   
  410.     /** 
  411.      * 这里演示利用Condition实现的自定义的队列 利用Condition创建不同的对象实现不同效果的通信,而不相互影响 
  412.      * 下面的代码直接取javaAPI的代码,因为这里思想确实很好,实现也简单 
  413.      * 这里演示的是自定义缓冲队列 
  414.      */  
  415.     class MyQueue {  
  416.         final Lock lock = new ReentrantLock();  
  417.         final Condition notFull = lock.newCondition();  
  418.         final Condition notEmpty = lock.newCondition();  
  419.   
  420.         // 缓冲队列,缓冲大小伟100  
  421.         final Object[] queue = new Object[100];  
  422.         int putIndex, getIndex, count;  
  423.   
  424.         // 存值  
  425.         public void put(Object x) throws InterruptedException {  
  426.             lock.lock();  
  427.             try {  
  428.                 // 若缓冲区已满,则notFull锁等待  
  429.                 while (count == queue.length) {  
  430.                     notFull.await();  
  431.                 }  
  432.                 if (++putIndex == queue.length) {  
  433.                     putIndex = 0// 若放到最后一个区间了,则再往第一个区间放  
  434.                 }  
  435.                 count++; // 代表放了一个数,唤醒取值线程去取  
  436.                 notEmpty.signal();  
  437.             } finally {  
  438.                 lock.unlock();  
  439.             }  
  440.         }  
  441.   
  442.         // 取值  
  443.         public Object get() throws InterruptedException {  
  444.             lock.lock();  
  445.             try {  
  446.                 // 若缓冲区没有数据满,则notEmpty锁等待  
  447.                 while (count == 0) {  
  448.                     notEmpty.await();  
  449.                 }  
  450.                 Object x = queue[getIndex]; // 取值  
  451.                 if (++getIndex == queue.length) {  
  452.                     getIndex = 0// 若取到最后一个区间了,则再从第一个区间取  
  453.                 }  
  454.                 count--; // 代表取放了一个数,唤醒放值线程  
  455.                 notFull.signal(); // 唤醒放值线程,可以放值了  
  456.                 return x;  
  457.             } finally {  
  458.                 lock.unlock();  
  459.             }  
  460.         }  
  461.     }  
  462.   
  463.     // -----------演示线程间变量共享,而保持内部数据独立-----------  
  464.   
  465.     /** 
  466.      * 定义一个全局ThreadLocal对象,注意:有多少个变量需要处理,就要定义多少个ThreadLocal 
  467.      * 即一个ThreadLocal只能管理一个变量,当然设计是你自己的问题(比如很多变量封装成一个对象,再用一个ThreadLocal来存放对象) 
  468.      */  
  469.     private static ThreadLocal<Integer> threadData = new ThreadLocal<Integer>();  
  470.   
  471.     /** 
  472.      * 这里主要演示ThreadLocal类的使用, 当然我们实现线程变量共享又保持数据相对独立,可以使用全局map为每个线程保存自己的那一份数据 
  473.      * 但这里直接使用ThreadLocal操作更加简便,并且线程终止时会自动释放内存,方便管理 
  474.      */  
  475.     public void thread_dataLocal() {  
  476.   
  477.         // 定义两个线程,分别存放自己的随机值,然后分别调用取值函数去取  
  478.         // 测试是否自己取出来的是自己存放的数据  
  479.         for (int i = 0; i < 2; i++) {  
  480.             new Thread(new Runnable() {  
  481.   
  482.                 @Override  
  483.                 public void run() {  
  484.                     int data = new Random().nextInt();  
  485.                     System.out.println(Thread.currentThread().getName() + " put data: " + data);  
  486.                     threadData.set(data);// 将数据交给ThreadLocal管理,内部跟map原理相似  
  487.                     new GetA().get();  
  488.                     new GetB().get();  
  489.                 }  
  490.             }).start();  
  491.         }  
  492.     }  
  493.   
  494.     /** 
  495.      * 定义获取线程的值 
  496.      */  
  497.     static class GetA {  
  498.         public void get() {  
  499.             int data = threadData.get();// 会直接根据当前调用线程取出  
  500.             System.out.println(Thread.currentThread().getName() + " get data of A:" + data);  
  501.         }  
  502.     }  
  503.   
  504.     /** 
  505.      * 同上 
  506.      */  
  507.     static class GetB {  
  508.         public void get() {  
  509.             int data = threadData.get();  
  510.             System.out.println(Thread.currentThread().getName() + " get data of B:" + data);  
  511.         }  
  512.     }  
  513.   
  514.     /** 
  515.      * 这里介绍封装多个变量数据的方法,这种设计很好,在对象内部封装ThreadLocal 
  516.      */  
  517.     static class MyThreadScopeData {  
  518.   
  519.         // 构造方法私有化  
  520.         private MyThreadScopeData() {  
  521.         };  
  522.   
  523.         // 以线程为key放置数据对象  
  524.         private static ThreadLocal<MyThreadScopeData> myThreadData = new ThreadLocal<MyThreadScopeData>();  
  525.   
  526.         // 单个线程内单例,好就好在这,每个线程独自单例  
  527.         public static MyThreadScopeData getInstanceForThread() {  
  528.             MyThreadScopeData scopeData = myThreadData.get();  
  529.             if (null == scopeData) {  
  530.                 scopeData = new MyThreadScopeData();  
  531.                 myThreadData.set(scopeData);  
  532.             }  
  533.             return scopeData;  
  534.         }  
  535.     }  
  536.   
  537.     // -----------演示线程原子性-----------  
  538.   
  539.     /** 
  540.      * 将普通基本变量封装成原执性,实现在线程间互斥 
  541.      */  
  542.     public void thread_atomic() {  
  543.   
  544.         // 定义原子性int变量,并初始化为0  
  545.         AtomicInteger atomicInt = new AtomicInteger(0);  
  546.         atomicInt.addAndGet(2); // +2  
  547.         atomicInt.addAndGet(-2); // -2  
  548.         atomicInt.decrementAndGet(); // -1  
  549.     }  
  550.   
  551.     // -----------演示线程池-----------  
  552.   
  553.     /** 
  554.      * 线程池的使用 创建线程池的方法大概有下面几种,这里简单介绍下 
  555.      */  
  556.     public void thread_pool() {  
  557.   
  558.         // 创建一个拥有5个线程的线程池(固定线程池)  
  559.         ExecutorService threadPool = Executors.newFixedThreadPool(5);  
  560.   
  561.         // 创建一个缓冲线程池,这样会随着任务增多,线程池中线程会自动变更  
  562.         ExecutorService threadPool2 = Executors.newCachedThreadPool();  
  563.   
  564.         // 特殊线程池,内部始终仅保持一个也仅有一个线程(死了会自动新创建一个)  
  565.         ExecutorService threadPool3 = Executors.newSingleThreadExecutor();  
  566.   
  567.         // 定时任务线程池,会调用内部线程中的一个或几个去定时执行任务,调用schedule()方法会执行任务  
  568.         ExecutorService threadPool4 = Executors.newScheduledThreadPool(6);  
  569.   
  570.         // 定义10个任务  
  571.         for (int i = 0; i < 10; i++) {  
  572.   
  573.             final int task = i; // 供任务内部调用  
  574.   
  575.             // 执行任务,这里会随机去5个线程中的一个执行  
  576.             threadPool.execute(new Runnable() {  
  577.                 @Override  
  578.                 public void run() {  
  579.                     System.out.println("第" + task + "个任务被" + Thread.currentThread().getName() + "执行");  
  580.                 }  
  581.             });  
  582.         }  
  583.         threadPool.shutdown();// 执行完任务关闭线程池  
  584.         threadPool.shutdownNow(); // 不管有没有执行完,立马关闭  
  585.     }  
  586.   
  587.     // -----------演示线程回调任务执行结果-----------  
  588.   
  589.     /** 
  590.      * Callable 与 Future 成对使用,一个返回回调结果,一个获取结果 更多操作查看API 
  591.      */  
  592.     public void thread_callableAndFuture() {  
  593.         ExecutorService threadPool = Executors.newSingleThreadExecutor();  
  594.   
  595.         // 通过线程submit的执行任务并返回回调结果,结果保存在Future中  
  596.         Future<String> future = threadPool.submit(new Callable<String>() {  
  597.             @Override  
  598.             public String call() throws Exception {  
  599.                 return "call回调返回的值";  
  600.             }  
  601.         });  
  602.   
  603.         try {  
  604.             String result = future.get(); // 获取回调结果  
  605.             System.out.println("回调结果:" + result);  
  606.         } catch (Exception e) {  
  607.             e.printStackTrace();  
  608.         }  
  609.     }  
  610.   
  611.     /** 
  612.      * CompletionService 用于提交一组callable任务,其take方法用于返回一个已完成的callable任务 
  613.      */  
  614.     public void thread_completionService() throws InterruptedException, ExecutionException {  
  615.         // 创建一个拥有5个线程的线程池(固定线程池,CompletionService会使用线程池中的线程去执行任务)  
  616.         ExecutorService threadPool = Executors.newFixedThreadPool(5);  
  617.   
  618.         CompletionService<String> completionService = new ExecutorCompletionService<String>(threadPool);  
  619.   
  620.         for (int i = 0; i < 10; i++) {  
  621.             final int task = i;  
  622.   
  623.             completionService.submit(new Callable<String>() {  
  624.                 @Override  
  625.                 public String call() throws Exception {  
  626.                     return Thread.currentThread().getName() + "回调结果:" + task;  
  627.                 }  
  628.             });  
  629.         }  
  630.   
  631.         // 拿10遍结果  
  632.         for (int i = 0; i < 10; i++) {  
  633.             System.out.println(completionService.take().get());  
  634.             completionService.take().get();// 捕获结果  
  635.         }  
  636.     }  
  637.   
  638.     // -----------演示线程信号灯的使用----------  
  639.   
  640.     /** 
  641.      * 线程之间的信号灯的使用,可以实现一个事件在同一时刻被多少个线程访问。 
  642.      * 
  643.      * @param args 
  644.      */  
  645.     public void thread_semaphore() {  
  646.   
  647.         // 线程池  
  648.         ExecutorService service = Executors.newCachedThreadPool();  
  649.   
  650.         // 定义4个信号灯  
  651.         final Semaphore semaphore = new Semaphore(4);  
  652.         // final Semaphore semaphore = new Semaphore(4,true); //true:是否保证先来先得  
  653.   
  654.         // 定义10个任务,但每次只能有三个任务被同时执行(信号灯控制)  
  655.         for (int i = 0; i < 20; i++) {  
  656.             Runnable runnable = new Runnable() {  
  657.                 @Override  
  658.                 public void run() {  
  659.                     try {  
  660.                         semaphore.acquire(); // 点亮信号灯,代表一个坑被占  
  661.                     } catch (InterruptedException e1) {  
  662.                         e1.printStackTrace();  
  663.                     }  
  664.                     System.out.println("线程" + Thread.currentThread().getName() + "进入,当前已有" + (3 - semaphore.availablePermits()) + "个并发");  
  665.                     try {  
  666.                         Thread.sleep((long) (Math.random() * 10000));  
  667.                     } catch (InterruptedException e) {  
  668.                         e.printStackTrace();  
  669.                     }  
  670.                     System.out.println("线程" + Thread.currentThread().getName() + "即将离开");  
  671.                     semaphore.release(); // 熄灭信号灯,代表一个坑被释放  
  672.   
  673.                     System.out.println("线程" + Thread.currentThread().getName() + "已离开,当前已有" + (3 - semaphore.availablePermits()) + "个并发");  
  674.                 }  
  675.             };  
  676.             service.execute(runnable);  
  677.         }  
  678.   
  679.         try {  
  680.             Thread.sleep((long) (Math.random() * 100000));  
  681.             service.shutdown();  
  682.         } catch (InterruptedException e) {  
  683.             e.printStackTrace();  
  684.         }  
  685.   
  686.     }  
  687.   
  688.     // -----------演示线程“同步”进行任务----------  
  689.   
  690.     /** 
  691.      * CyclicBarrier同步工具 表示要求一定数量线程同时到达某一状态才继续一起往下执行,否则就等待其他行程 中间可以设置多个状态 
  692.      * 如:完成各自的任务后集合吃饭,吃晚饭后又各自做自己的事 
  693.      */  
  694.     public void thread_cyclicBarrier() {  
  695.   
  696.         ExecutorService service = Executors.newCachedThreadPool();  
  697.   
  698.         // 定义CyclicBarrier同步工具,表示要有5个线程同时到达某一状态才继续一起往下执行,否则就等待其他行程  
  699.         final CyclicBarrier cyclicBarrier = new CyclicBarrier(5);  
  700.         for (int i = 0; i < 5; i++) {  
  701.             Runnable runnable = new Runnable() {  
  702.                 @Override  
  703.                 public void run() {  
  704.                     try {  
  705.                         Thread.sleep((long) (Math.random() * 10000));  
  706.                         System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点1,当前已有" + (cyclicBarrier.getNumberWaiting() + 1) + "个已经到达,"  
  707.                                 + (cyclicBarrier.getNumberWaiting() == 4 ? "都到齐了,可以走了" : "等候其他线程"));  
  708.   
  709.                         // (第一个集合点)没到达就要等候  
  710.                         cyclicBarrier.await();  
  711.   
  712.                         Thread.sleep((long) (Math.random() * 10000));  
  713.                         System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点2,当前已有" + (cyclicBarrier.getNumberWaiting() + 1) + "个已经到达,"  
  714.                                 + (cyclicBarrier.getNumberWaiting() == 4 ? "都到齐了,可以走了" : "等候其他线程"));  
  715.   
  716.                         // (第二个集合点)没到达就要等候  
  717.                         cyclicBarrier.await();  
  718.   
  719.                         Thread.sleep((long) (Math.random() * 10000));  
  720.                         System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点3,当前已有" + (cyclicBarrier.getNumberWaiting() + 1) + "个已经到达,"  
  721.                                 + (cyclicBarrier.getNumberWaiting() == 4 ? "都到齐了,可以走了" : "等候其他线程"));  
  722.                         cyclicBarrier.await();  
  723.                     } catch (Exception e) {  
  724.                         e.printStackTrace();  
  725.                     }  
  726.                 }  
  727.             };  
  728.             service.execute(runnable);  
  729.         }  
  730.   
  731.         service.shutdown();  
  732.         // try {  
  733.         // Thread.sleep((long)(Math.random()*10000));  
  734.         // // service.shutdown();  
  735.         // } catch (InterruptedException e) {  
  736.         // e.printStackTrace();  
  737.         // }  
  738.   
  739.     }  
  740.   
  741.     // -----------演示线程“倒计时”命令----------  
  742.   
  743.     /** 
  744.      * CountDownLatch可以实现倒计时 
  745.      * CountDownLatch.countDown()可以将时间减1,直到0时,所有线程可以进行下去,否则阻塞。 下面实现裁判员跟运动员的关系 
  746.      * 
  747.      * @param args 
  748.      */  
  749.     public void thread_countDownLatch() {  
  750.         ExecutorService service = Executors.newCachedThreadPool();  
  751.   
  752.         // 倒计时1:初始化为1,当裁判员发动命令时,便调用countDown()减到0,这时促使运动员执行  
  753.         final CountDownLatch cdOrder = new CountDownLatch(1);  
  754.   
  755.         // 倒计时2:初始化为3,代表三个运动员,但每个运动员执行完,计数器便减1,当所有运动员执行完,便告知裁判员已完成  
  756.         final CountDownLatch cdAnswer = new CountDownLatch(3);  
  757.         for (int i = 0; i < 3; i++) {  
  758.             Runnable runnable = new Runnable() {  
  759.                 public void run() {  
  760.                     try {  
  761.                         Thread.sleep((long) (Math.random() * 10000));  
  762.   
  763.                         System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令");  
  764.   
  765.                         cdOrder.await();// 等待裁判员命令,只要计数器不为0,就一直等待  
  766.   
  767.                         System.out.println("线程" + Thread.currentThread().getName() + "已接受命令");  
  768.   
  769.                         Thread.sleep((long) (Math.random() * 10000));  
  770.   
  771.                         System.out.println("线程" + Thread.currentThread().getName() + "执行完");  
  772.   
  773.                         cdAnswer.countDown(); // 每执行完一个,裁判员计数器便减1  
  774.   
  775.                     } catch (Exception e) {  
  776.                         e.printStackTrace();  
  777.                     }  
  778.                 }  
  779.             };  
  780.             service.execute(runnable);  
  781.         }  
  782.   
  783.         try {  
  784.             Thread.sleep((long) (Math.random() * 10000));  
  785.   
  786.             System.out.println("线程" + Thread.currentThread().getName() + "准备发布命令");  
  787.   
  788.             cdOrder.countDown();// 减1,代表裁判员发动命令  
  789.   
  790.             System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果");  
  791.   
  792.             cdAnswer.await();// 等待计数器为0,即等待所有运动员全部执行完  
  793.   
  794.             System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果");  
  795.         } catch (Exception e) {  
  796.             e.printStackTrace();  
  797.         }  
  798.         service.shutdown();  
  799.     }  
  800.   
  801.     // -----------演示线程间的数据交换----------  
  802.   
  803.     /** 
  804.      * Exchanger可以实现线程间的数据交换,只要有一方数据没到,另一方就一直等待,但同时到达时才进行数据交换 
  805.      * 
  806.      * @param args 
  807.      */  
  808.     public void thread_exchanger() {  
  809.   
  810.         ExecutorService service = Executors.newCachedThreadPool();  
  811.   
  812.         // 交换器  
  813.         final Exchanger<String> exchanger = new Exchanger<String>();  
  814.   
  815.         // 运行第一个线程  
  816.         service.execute(new Runnable() {  
  817.             public void run() {  
  818.                 try {  
  819.   
  820.                     String data1 = "线程1的数据";  
  821.                     System.out.println("线程" + Thread.currentThread().getName() + "正在把数据:" + data1 + " 换出去");  
  822.                     Thread.sleep((long) (Math.random() * 10000));  
  823.   
  824.                     // 线程1数据到了  
  825.                     String data2 = (String) exchanger.exchange(data1);  
  826.   
  827.                     System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为:" + data2);  
  828.                 } catch (Exception e) {  
  829.   
  830.                 }  
  831.             }  
  832.         });  
  833.   
  834.         // 运行第二个线程  
  835.         service.execute(new Runnable() {  
  836.             public void run() {  
  837.                 try {  
  838.   
  839.                     String data1 = "线程2的数据";  
  840.                     System.out.println("线程" + Thread.currentThread().getName() + "正在把数据:" + data1 + " 换出去");  
  841.                     Thread.sleep((long) (Math.random() * 10000));  
  842.   
  843.                     // 线程2数据到了  
  844.                     String data2 = (String) exchanger.exchange(data1);  
  845.   
  846.                     System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为:" + data2);  
  847.                 } catch (Exception e) {  
  848.   
  849.                 }  
  850.             }  
  851.         });  
  852.   
  853.         try {  
  854.             Thread.sleep((long) (Math.random() * 100000));  
  855.         } catch (Exception e) {  
  856.             e.printStackTrace();  
  857.         }  
  858.     }  
  859.   
  860.     // -----------演示同步集合----------  
  861.   
  862.     /** 
  863.      * 同步集合 无可厚非,同步集合当然表示集合的读写安全 这样不用自己去处理,很方便管理,但场合是否真正需要要自己把握 
  864.      */  
  865.     public void thread_syncCollection() {  
  866.   
  867.         // 同步Map  
  868.         Map<String, String> syncMap = new ConcurrentHashMap<String, String>();  
  869.   
  870.         // 方式2  
  871.         Map<String, String> map = new HashMap<String, String>();  
  872.         Map<String, String> syncMap2 = new ConcurrentHashMap<String, String>(map);  
  873.   
  874.         // 同步List  
  875.         List<String> syncList = new CopyOnWriteArrayList<String>();  
  876.   
  877.         // 方式2  
  878.         List<String> list = new CopyOnWriteArrayList<String>();  
  879.         List<String> syncList2 = new CopyOnWriteArrayList<String>(list);  
  880.   
  881.         // 同步Set  
  882.         Set<String> syncSet = new CopyOnWriteArraySet<String>();  
  883.   
  884.         // 方式2  
  885.         Set<String> set = new CopyOnWriteArraySet<String>();  
  886.         Set<String> syncSet2 = new CopyOnWriteArraySet<String>(set);  
  887.   
  888.     }  
  889.   
  890. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值