線程學習筆記-只是簡單的應用

 原文:https://www.cnblogs.com/riskyer/p/3263032.html
1
/** 2 * 線程同步 synchronized 的使用方法 問題:倆個線程調用同一個方法,要經過同步關鍵字實現 鎖。使的方法結果正確 3 * 4 * 預期結果: 5 * test-1 :當前foo對象的x值= 70 test-1 :當前foo對象的x值= 40 test-1 :當前foo對象的x值= 10 6 * test-2 :當前foo對象的x值= -20 test-2 :當前foo對象的x值= -50 test-2 :當前foo對象的x值= -80 7 * 8 */ 9 public class ThreadSynchronized { 10 public static class Foo { 11 private int x = 100; 12 13 public int getX() { 14 return x; 15 } 16 17 public int fix(int y) { 18 x = x - y; 19 return x; 20 } 21 22 } 23 24 public static void main(String[] args) { 25 26 Runnable r = new Runnable() { 27 private Foo foo = new Foo(); 28 29 @Override 30 public void run() { 31 //原理就是給對象上鎖,有鑰匙的線程才能執行方法,保證一次只會進入一個線程 32 synchronized (foo) { 33 for (int i = 0; i < 3; i++) { 34 foo.fix(30); 35 System.out.println(Thread.currentThread().getName() + " :當前foo對象的x值= " + foo.getX()); 36 } 37 } 38 } 39 }; 40 41 //這個是給線程起名字,線程默認也會給本身取名字的 42 Thread a = new Thread(r, "test-1"); 43 Thread b = new Thread(r, "test-2"); 44 a.start(); 45 b.start(); 46 47 } 48 }

 

  1 import java.util.concurrent.Callable;
  2 import java.util.concurrent.ExecutionException;
  3 import java.util.concurrent.ExecutorService;
  4 import java.util.concurrent.Executors;
  5 import java.util.concurrent.Future;
  6 
  7 
  8 /**
  9  * 爲何要使用線程池? 爲了減小建立和銷燬線程的次數,讓每一個線程能夠屢次使用,可根據系統狀況調整執行的線程數量,防止消耗過多內存,因此咱們可使用線程池.
 10  * 
 11  * java中線程池的頂級接口是Executor(e可rai kei
 12  * ter),ExecutorService是Executor的子類,也是真正的線程池接口,它提供了提交任務和關閉線程池等方法。調用submit方法提交任務還能夠返回一個Future(fei
 13  * 曲兒)對象,利用該對象能夠了解任務執行狀況,得到任務的執行結果或取消任務。
 14  * 
 15  * 因爲線程池的配置比較複雜,JavaSE中定義了Executors類就是用來方便建立各類經常使用線程池的工具類。經過調用該工具類中的方法咱們能夠建立單線程池(newSingleThreadExecutor),固定數量的線程池(newFixedThreadPool),可緩存線程池(newCachedThreadPool),大小無限制的線程池(newScheduledThreadPool),比較經常使用的是固定數量的線程池和可緩存的線程池,固定數量的線程池是每提交一個任務就是一個線程,直到達到線程池的最大數量,而後後面進入等待隊列直到前面的任務完成才繼續執行.可緩存線程池是當線程池大小超過了處理任務所需的線程,那麼就會回收部分空閒(通常是60秒無執行)的線程,當有任務來時,又智能的添加新線程來執行.
 16  * 
 17  * 
 18  * 
 19  * Executors類中還定義了幾個線程池重要的參數,好比說int corePoolSize核心池的大小,也就是線程池中會維持不被釋放的線程數量.int
 20  * maximumPoolSize線程池的最大線程數,表明這線程池彙總能建立多少線程。corePoolSize
 21  * :核心線程數,若是運行的線程數少corePoolSize,當有新的任務過來時會建立新的線程來執行這個任務,即便線程池中有其餘的空閒的線程。maximumPoolSize:線程池中容許的最大線程數.
 22  *
 23  */
 24 public class ThreadPool {
 25 
 26     
 27     public static void main(String[] args) throws InterruptedException, ExecutionException {
 28 
 29         Thread t1 = new Thread(() -> {
 30             System.out.println(Thread.currentThread().getName() + " t1");
 31         });
 32 
 33         Thread t2 = new Thread(() -> {
 34             System.out.println(Thread.currentThread().getName() + " t2");
 35         });
 36 
 37         Thread t3 = new Thread(() -> {
 38             System.out.println(Thread.currentThread().getName() + " t3");
 39         });
 40 
 41         /**
 42          * 固定線程池:newFixedThreadPool
 43          * 
 44          * 當線程池大小爲小於線程個數 
 45          * pool-1-thread-1 t1 
 46          * pool-1-thread-1 t2 
 47          * pool-1-thread-1 t3
 48          * 
 49          * 當線程池大小大於等於線程個數
 50          * 
 51          * pool-1-thread-2 t2 
 52          * pool-1-thread-3 t3 
 53          * pool-1-thread-1 t1
 54          * 
 55          * 對於以上兩種鏈接池,大小都是固定的,當要加入的池的線程(或者任務)超過池最大尺寸時候,則入此線程池須要排隊等待。
 56          * 一旦池中有線程完畢,則排隊等待的某個線程會入池執行。
 57          * 
 58          */
 59 //        ExecutorService pool = Executors.newFixedThreadPool(10);
 60 //        pool.execute(t1);
 61 //        pool.execute(t2);
 62 //        pool.execute(t3);
 63 //        pool.shutdown();
 64         
 65         /**
 66          * 單任務線程池:newSingleThreadExecutor
 67          * 結果:
 68          * pool-1-thread-1 t1
 69          * pool-1-thread-1 t2
 70          * pool-1-thread-1 t3
 71          */
 72 //        ExecutorService pool = Executors.newSingleThreadExecutor();
 73 //        pool.execute(t1);
 74 //        pool.execute(t2);
 75 //        pool.execute(t3);
 76 //        pool.shutdown();
 77         
 78         /**
 79          * 以上倆種都是固定大小的線程池
 80          * 如今說一下可變大小的線程池:
 81          * newCachedThreadPool:根據須要建立線程池
 82          * pool-1-thread-1 t1
 83          * pool-1-thread-3 t3
 84          * pool-1-thread-2 t2
 85          */
 86 //        ExecutorService pool = Executors.newCachedThreadPool();
 87 //        pool.execute(t1);
 88 //        pool.execute(t2);
 89 //        pool.execute(t3);
 90 //        pool.shutdown();
 91         
 92         /**
 93          * newScheduledThreadPool:延遲鏈接池
 94          * pool-1-thread-1 t1
 95            * pool-1-thread-2 t2
 96           * pool-1-thread-1 t3
 97          * pool-1-thread-2 t1
 98          * pool-1-thread-1 t2
 99          * pool-1-thread-2 t3
100          */
101 //        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
102         //放入線程池中執行
103 //        pool.execute(t1);
104 //        pool.execute(t2);
105 //        pool.execute(t3);
106         //使用延遲執行
107 //        pool.schedule(t1, 10, TimeUnit.SECONDS);
108 //        pool.schedule(t2, 10, TimeUnit.SECONDS);
109 //        pool.schedule(t3, 10, TimeUnit.SECONDS);
110 //        pool.shutdown();
111         
112         /**
113          * newSingleThreadScheduledExecutor:單任務延遲線程池
114          * pool-1-thread-1 t1
115          * pool-1-thread-1 t2
116          * pool-1-thread-1 t3
117          * pool-1-thread-1 t1
118          * pool-1-thread-1 t2
119          * pool-1-thread-1 t3
120          */
121 //        ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
122 //        //放入線程池中執行
123 //        pool.execute(t1);
124 //        pool.execute(t2);
125 //        pool.execute(t3);
126 //        //使用延遲執行
127 //        pool.schedule(t1, 10, TimeUnit.SECONDS);
128 //        pool.schedule(t2, 10, TimeUnit.SECONDS);
129 //        pool.schedule(t3, 10, TimeUnit.SECONDS);
130 //        pool.shutdown();
131         
132         /**
133          * ThreadPoolExecutor:自定義線程池
134          */
135 //        BlockingQueue<Runnable> bQueue = new ArrayBlockingQueue<>(20);
136 //        ThreadPoolExecutor pool = new ThreadPoolExecutor(1,3 , 10, TimeUnit.MILLISECONDS, bQueue);
137 //        pool.execute(t1);
138 //        pool.execute(t2);
139 //        pool.execute(t3);
140 //        pool.shutdown();
141         /**
142          * 在這多說一句:自定義線程池涉及到拒絕策略
143          * 當線程池的任務緩存隊列已滿而且線程池中的線程數目達到maximumPoolSize時,
144          * 若是還有任務到來就會採起任務拒絕策略,一般有如下四種策略:
145          * ThreadPoolExecutor.AbortPolicy:丟棄任務並拋出
146          * RejectedExecutionException異常。 
147          * ThreadPoolExecutor.DiscardPolicy:丟棄任務,可是不拋出異常。 
148          * ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務,而後從新提交被拒絕的任務 
149          * ThreadPoolExecutor.CallerRunsPolicy:由調用線程(提交任務的線程)處理該任務 
150          * 
151          * (1)AbortPolicy
152          * ThreadPoolExecutor.AbortPolicy:丟棄任務並拋出RejectedExecutionException異常。
153          * A handler for rejected tasks that throws a {@code RejectedExecutionException}.
154          * 這是線程池默認的拒絕策略,在任務不能再提交的時候,拋出異常,及時反饋程序運行狀態。若是是比較關鍵的業務,推薦使用此拒絕策略,這樣子在系統不能承載更大的併發量的時候,可以及時的經過異常發現。
155          * (2)DiscardPolicy
156          * ThreadPoolExecutor.DiscardPolicy:丟棄任務,可是不拋出異常。若是線程隊列已滿,則後續提交的任務都會被丟棄,且是靜默丟棄。
157          * A handler for rejected tasks that silently discards therejected task.
158          * 使用此策略,可能會使咱們沒法發現系統的異常狀態。建議是一些可有可無的業務採用此策略。例如,本人的博客網站統計閱讀量就是採用的這種拒絕策略。
159          * (3)DiscardOldestPolicy
160          * ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務,而後從新提交被拒絕的任務。
161          * A handler for rejected tasks that discards the oldest unhandled request and then retries {@code execute}, unless the executor is shut down, in which case the task is discarded.
162          * 此拒絕策略,是一種喜新厭舊的拒絕策略。是否要採用此種拒絕策略,還得根據實際業務是否容許丟棄老任務來認真衡量。
163          * (4)CallerRunsPolicy
164          * ThreadPoolExecutor.CallerRunsPolicy:由調用線程處理該任務
165          * A handler for rejected tasks that runs the rejected task directly in the calling thread of the {@code execute} method, unless the executor has been shut down, in which case the task is discarded.
166          * 若是任務被拒絕了,則由調用線程(提交任務的線程)直接執行此任務
167          */
168         
169         /*
170          * 獲取線程的返回值:須要實現
171          * 結果:A
172          */
173         Callable callable = new Callable<Object>() {
174             @Override
175             public Object call() throws Exception {
176                 return "A";
177             }
178         };
179         ExecutorService pool = Executors.newFixedThreadPool(2); 
180         Future f4 = pool.submit(callable);  
181         //這個獲取值有一個執行線程順序的坑,在異步的時候會出現,記不清啦
182         System.out.println(f4.get().toString());
183     }
184 }

 

  1 import java.util.concurrent.ExecutorService;
  2 import java.util.concurrent.Executors;
  3 import java.util.concurrent.locks.Lock;
  4 import java.util.concurrent.locks.ReentrantLock;
  5 
  6 /**
  7  * 在Java5中,專門提供了鎖對象,利用鎖能夠方便的實現資源的封鎖,用來控制對競爭資源併發訪問的控制,這些內容主要集中在java.util.concurrent.locks包下面,裏面有三個重要的接口Condition、Lock、ReadWriteLock。
  8  * 
  9  * 
 10  * 
 11  * Condition
 12  * 
 13  * Condition將Object監視器方法(wait、notify和
 14  * notifyAll)分解成大相徑庭的對象,以便經過將這些對象與任意Lock實現組合使用,爲每一個對象提供多個等待 set(wait-set)。
 15  * 
 16  * Lock
 17  * 
 18  * Lock實現提供了比使用synchronized方法和語句可得到的更普遍的鎖定操做。
 19  * 
 20  * ReadWriteLock
 21  * 
 22  * ReadWriteLock維護了一對相關的鎖定,一個用於只讀操做,另外一個用於寫入操做。
 23  *
 24  * 
 25  * 切記:鎖是針對對象的
 26  */
 27 public class ThreadLock {
 28 
 29     /**
 30      * 信用卡的用戶
 31      */
 32     static class User implements Runnable {
 33         private String name; // 用戶名
 34         private MyCount myCount; // 所要操做的帳戶
 35         private int iocash; // 操做的金額,固然有正負之分了
 36         private Lock myLock; // 執行操做所需的鎖對象
 37 
 38         User(String name, MyCount myCount, int iocash, Lock myLock) {
 39             this.name = name;
 40             this.myCount = myCount;
 41             this.iocash = iocash;
 42             this.myLock = myLock;
 43         }
 44 
 45         public void run() {
 46             // ’獲取鎖
 47             myLock.lock();
 48             myCount.setCash(myCount.getCash() + iocash);
 49             // ’執行現金業務
 50             System.out.println(name + "正在操做" + myCount + "帳戶,金額爲" + iocash + ",當前金額爲" + myCount.getCash());
 51             // ‘釋放鎖,不然別的線程沒有機會執行了
 52             myLock.unlock();
 53         }
 54     }
 55 
 56     /**
 57      * 信用卡帳戶,可隨意透支
 58      */
 59     static class MyCount {
 60         private String oid; // 帳號
 61         private int cash; // 帳戶餘額
 62 
 63         MyCount(String oid, int cash) {
 64             this.oid = oid;
 65             this.cash = cash;
 66         }
 67 
 68         public String getOid() {
 69             return oid;
 70         }
 71 
 72         public void setOid(String oid) {
 73             this.oid = oid;
 74         }
 75 
 76         public int getCash() {
 77             return cash;
 78         }
 79 
 80         public void setCash(int cash) {
 81             this.cash = cash;
 82         }
 83 
 84         @Override
 85         public String toString() {
 86             return "MyCount{" + "oid='" + oid + '\'' + ", cash=" + cash + '}';
 87         }
 88     }
 89 
 90     public static void main(String[] args) {
 91         // ’建立併發訪問的帳戶
 92         MyCount myCount = new MyCount("95599200901215522", 10000);
 93         // ‘建立一個鎖對象
 94         Lock lock = new ReentrantLock();
 95         // ‘建立一個線程池
 96         ExecutorService pool = Executors.newCachedThreadPool();
 97         //’建立一些併發訪問用戶,一個信用卡,存的存,取的取,好熱鬧啊
 98         User u1 = new User("張三", myCount, -4000, lock);
 99         User u2 = new User("張三他爹", myCount, 6000, lock);
100         User u3 = new User("張三他弟", myCount, -8000, lock);
101         User u4 = new User("張三", myCount, 800, lock);
102         // ’在線程池中執行各個用戶的操做
103         pool.execute(u1);
104         pool.execute(u2);
105         pool.execute(u3);
106         pool.execute(u4);
107         // ‘關閉線程池
108         pool.shutdown();
109     }
110 }

 

 1 import java.util.concurrent.ArrayBlockingQueue;
 2 import java.util.concurrent.BlockingQueue;
 3 
 4 /*
 5  * 阻塞隊列是Java5線程新特徵中的內容,Java定義了阻塞隊列的接口java.util.concurrent.BlockingQueue,阻塞隊列的概念是,一個指定長度的隊列,若是隊列滿了,添加新元素的操做會被阻塞等待,直到有空位爲止。一樣,當隊列爲空時候,請求隊列元素的操做一樣會阻塞等待,直到有可用元素爲止。
 6 
 7  
 8 
 9 有了這樣的功能,就爲多線程的排隊等候的模型實現開闢了便捷通道,很是有用。
10 
11  
12 
13 java.util.concurrent.BlockingQueue繼承了java.util.Queue接口,能夠參看API文檔。
14 
15 另外,阻塞隊列還有更多實現類,用來知足各類複雜的需求:ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue,具體的API差異也很小。
16  */
17 public class ThreadBlockingQueue {
18     public static void main(String[] args) throws InterruptedException {
19         BlockingQueue bqueue = new ArrayBlockingQueue<>(10);
20         for (int i = 0; i < 20; i++) {
21             bqueue.put(i);
22             System.err.println(i);
23         }
24         //’能夠看出,輸出到元素9時候,就一直處於等待狀態,由於隊列滿了,程序阻塞了。
25         System.out.println("exit");
26     }
27 }

 

 1 import java.util.concurrent.BlockingDeque;
 2 import java.util.concurrent.LinkedBlockingDeque;
 3 
 4 /**
 5  * 對於阻塞棧,與阻塞隊列類似。不一樣點在於棧是「後入先出」的結構,每次操做的是棧頂,而隊列是「先進先出」的結構,每次操做的是隊列頭。
 6  * 
 7  * 
 8  * 
 9  * 這裏要特別說明一點的是,阻塞棧是Java6的新特徵。、
10  * 
11  * 
12  * 
13  * Java爲阻塞棧定義了接口:java.util.concurrent.BlockingDeque,其實現類也比較多,具體能夠查看JavaAPI文檔。
14  * 
15  * 從上面結果能夠看到,程序並沒結束,二是阻塞住了,緣由是棧已經滿了,後面追加元素的操做都被阻塞了。
16  */
17 public class ThreadBlockingDeque {
18 
19     public static void main(String[] args) throws InterruptedException {
20         BlockingDeque bDeque = new LinkedBlockingDeque<>(10);
21         for (int i = 0; i < 20; i++) {
22             bDeque.putFirst(i);
23             System.err.println(i);
24         }
25         System.out.println("exit");
26     }
27 }

 

  1 import java.util.concurrent.ExecutorService;
  2 import java.util.concurrent.Executors;
  3 import java.util.concurrent.locks.Condition;
  4 import java.util.concurrent.locks.Lock;
  5 import java.util.concurrent.locks.ReentrantLock;
  6 
  7 /**
  8  * 條件變量是Java5線程中很重要的一個概念,顧名思義,條件變量就是表示條件的一種變量。可是必須說明,這裏的條件是沒有實際含義的,僅僅是個標記而已,而且條件的含義每每經過代碼來賦予其含義。
  9  * 
 10  * 
 11  * 
 12  * 這裏的條件和普通意義上的條件表達式有着天壤之別。
 13  * 
 14  * 
 15  * 
 16  * 條件變量都實現了java.util.concurrent.locks.Condition接口,條件變量的實例化是經過一個Lock對象上調用newCondition()方法來獲取的,這樣,條件就和一個鎖對象綁定起來了。所以,Java中的條件變量只能和鎖配合使用,來控制併發程序訪問競爭資源的安全。
 17  * 
 18  * 
 19  * 
 20  * 條件變量的出現是爲了更精細控制線程等待與喚醒,在Java5以前,線程的等待與喚醒依靠的是Object對象的wait()和notify()/notifyAll()方法,這樣的處理不夠精細。
 21  * 
 22  * 
 23  * 
 24  * 而在Java5中,一個鎖能夠有多個條件,每一個條件上能夠有多個線程等待,經過調用await()方法,可讓線程在該條件下等待。當調用signalAll()方法,又能夠喚醒該條件下的等待的線程。有關Condition接口的API能夠具體參考JavaAPI文檔。
 25  * 
 26  * 
 27  * 
 28  * 條件變量比較抽象,緣由是他不是天然語言中的條件概念,而是程序控制的一種手段。
 29  * 
 30  * 
 31  * 
 32  * 下面以一個銀行存取款的模擬程序爲例來揭蓋Java多線程條件變量的神祕面紗:
 33  * 
 34  * 
 35  * 
 36  * 有一個帳戶,多個用戶(線程)在同時操做這個帳戶,有的存款有的取款,存款隨便存,取款有限制,不能透支,任何試圖透支的操做都將等待裏面有足夠存款才執行操做。
 37  *
 38  */
 39 public class ThreadCondition {
 40     static class MyAccount {
 41         private String oid;
 42         private int cash;
 43         private Lock lock = new ReentrantLock();
 44         private Condition _save = lock.newCondition();
 45         private Condition _draw = lock.newCondition();
 46 
 47         public String getOid() {
 48             return oid;
 49         }
 50 
 51         public void setOid(String oid) {
 52             this.oid = oid;
 53         }
 54 
 55         public int getCash() {
 56             return cash;
 57         }
 58 
 59         public void setCash(int cash) {
 60             this.cash = cash;
 61         }
 62 
 63         public MyAccount(String oid, int cash) {
 64             super();
 65             this.oid = oid;
 66             this.cash = cash;
 67         }
 68 
 69         public void saving(int x, String name) {
 70             lock.lock();
 71             setCash(cash + x);
 72             System.out.println(Thread.currentThread().getName() + " name " + name + "x " + x + " ,cash " + cash);
 73             _draw.signalAll();
 74             lock.unlock();
 75         }
 76 
 77         public void drawing(int x, String name) {
 78             lock.lock();
 79             try {
 80                 while (cash - x < 0) {
 81                     _draw.await();
 82                     _save.signalAll();
 83                 }
 84                 setCash(cash - x);
 85                 System.out.println(Thread.currentThread().getName() + " name " + name + "x " + x + " ,cash " + cash);
 86             } catch (InterruptedException e) {
 87                 // TODO Auto-generated catch block
 88                 e.printStackTrace();
 89             } finally {
 90                 lock.unlock();
 91             }
 92 
 93         }
 94 
 95     }
 96 
 97     static class SaveThread extends Thread {
 98         private String name;
 99         private MyAccount myAccount;
100         private int x;
101 
102         public SaveThread(String name, MyAccount myAccount, int x) {
103             super();
104             this.name = name;
105             this.myAccount = myAccount;
106             this.x = x;
107         }
108 
109         @Override
110         public void run() {
111             myAccount.saving(x, name);
112         }
113 
114     }
115 
116     static class DrawThread extends Thread {
117         private String name;
118         private MyAccount myAccount;
119         private int x;
120 
121         public DrawThread(String name, MyAccount myAccount, int x) {
122             super();
123             this.name = name;
124             this.myAccount = myAccount;
125             this.x = x;
126         }
127 
128         @Override
129         public void run() {
130             myAccount.drawing(x, name);
131         }
132     }
133 
134     public static void main(String[] args) {
135         // ‘建立併發訪問的帳戶
136         MyAccount myAccount = new MyAccount("95599200901215522", 10000);
137         // ’ 建立一個線程池
138         ExecutorService pool = Executors.newFixedThreadPool(12);
139         Thread t1 = new SaveThread("張三", myAccount, 2000);
140         Thread t2 = new SaveThread("李四", myAccount, 3600);
141         Thread t3 = new DrawThread("王五", myAccount, 2700);
142         Thread t4 = new SaveThread("老張", myAccount, 600);
143         Thread t5 = new DrawThread("老牛", myAccount, 1300);
144         Thread t6 = new DrawThread("胖子", myAccount, 800);
145         // ‘ 執行各個線程
146         pool.execute(t1);
147         pool.execute(t2);
148         pool.execute(t3);
149         pool.execute(t4);
150         pool.execute(t5);
151         pool.execute(t6);
152         // ’ 關閉線程池
153         pool.shutdown();
154     }
155 }

 

 1 import java.util.concurrent.ExecutorService;
 2 import java.util.concurrent.Executors;
 3 import java.util.concurrent.atomic.AtomicLong;
 4 import java.util.concurrent.locks.Lock;
 5 import java.util.concurrent.locks.ReentrantLock;
 6 
 7 /**
 8  * 
 9  * Java線程:新特徵-原子量 所謂的原子量即操做變量的操做是「原子的」,該操做不可再分,所以是線程安全的。
10  * 
11  * 
12  * 
13  * 爲什麼要使用原子變量呢,緣由是多個線程對單個變量操做也會引發一些問題。在Java5以前,能夠經過volatile、synchronized關鍵字來解決併發訪問的安全問題,但這樣太麻煩。
14  * 
15  * Java5以後,專門提供了用來進行單變量多線程併發安全訪問的工具包java.util.concurrent.atomic,其中的類也很簡單。
16  * 
17  * 這裏使用了一個對象鎖,來控制對併發代碼的訪問。無論運行多少次,執行次序如何,最終餘額均爲21000,這個結果是正確的。
18  * 
19  * 
20  * 
21  * 有關原子量的用法很簡單,關鍵是對原子量的認識,原子僅僅是保證變量操做的原子性,但整個程序還須要考慮線程安全的。
22  */
23 public class ThreadAtomic {
24 
25     static class MyRunnable implements Runnable {
26         private AtomicLong atomicLong = new AtomicLong(10000);
27 
28         private String name; // 操做人
29         private int x; // 操做數額
30         private Lock lock = new ReentrantLock();
31 
32         public String getName() {
33             return name;
34         }
35 
36         public void setName(String name) {
37             this.name = name;
38         }
39 
40         public int getX() {
41             return x;
42         }
43 
44         public void setX(int x) {
45             this.x = x;
46         }
47 
48         public MyRunnable(String name, int x) {
49             super();
50             this.name = name;
51             this.x = x;
52         }
53 
54         @Override
55         public void run() {
56             lock.lock();
57             System.out.println(Thread.currentThread().getName() + " name: " + name + " x " + x + " 執行啦 "
58                     + atomicLong.addAndGet(x));
59             lock.unlock();
60         }
61 
62     }
63 
64     public static void main(String[] args) {
65         ExecutorService pool = Executors.newFixedThreadPool(2);
66 //           Lock lock = new ReentrantLock(false);
67         Runnable t1 = new MyRunnable("張三", 2000);
68         Runnable t2 = new MyRunnable("李四", 3600);
69         Runnable t3 = new MyRunnable("王五", 2700);
70         Runnable t4 = new MyRunnable("老張", 600);
71         Runnable t5 = new MyRunnable("老牛", 1300);
72         Runnable t6 = new MyRunnable("胖子", 800);
73         // 執行各個線程
74         pool.execute(t1);
75         pool.execute(t2);
76         pool.execute(t3);
77         pool.execute(t4);
78         pool.execute(t5);
79         pool.execute(t6);
80         // 關閉線程池
81         pool.shutdown();
82 
83     }
84 }

 

 1 import java.util.concurrent.BrokenBarrierException;
 2 import java.util.concurrent.CyclicBarrier;
 3 
 4 /**
 5  * java5中,添加了障礙器類,爲了適應一種新的設計需求,好比一個大型的任務,經常須要分配好多子任務去執行,只有當全部子任務都執行完成時候,才能執行主任務,這時候,就能夠選擇障礙器了。
 6  * 全部子任務完成的時候,主任務執行了,達到了控制的目標。
 7  */
 8 public class ThreadCyclicBarrier {
 9     static class MainTask implements Runnable {
10 
11         @Override
12         public void run() {
13             System.out.println("mainTask");
14         }
15 
16     }
17 
18     static class SubTask extends Thread {
19         private CyclicBarrier cb;
20         private String name;
21 
22         public SubTask(String name, CyclicBarrier cb) {
23             super();
24             this.cb = cb;
25             this.name = name;
26         }
27 
28         @Override
29         public void run() {
30 
31             try {
32                 System.out.println(name);
33                 cb.await();
34             } catch (InterruptedException e) {
35                 // TODO Auto-generated catch block
36                 e.printStackTrace();
37             } catch (BrokenBarrierException e) {
38                 // TODO Auto-generated catch block
39                 e.printStackTrace();
40             }
41         }
42     }
43 
44     public static void main(String[] args) {
45         // 建立障礙器,並設置MainTask爲全部定數量的線程都達到障礙點時候所要執行的任務(Runnable)
46         CyclicBarrier cb = new CyclicBarrier(7, new MainTask());
47         new SubTask("A", cb).start();
48         new SubTask("B", cb).start();
49         new SubTask("C", cb).start();
50         new SubTask("D", cb).start();
51         new SubTask("E", cb).start();
52         new SubTask("F", cb).start();
53         new SubTask("G", cb).start();
54     }
55 }
相關文章
相關標籤/搜索