Java Concurrent并发库实例

来源:互联网 发布:培训学校课时软件 编辑:程序博客网 时间:2024/06/17 10:56
 

Java Concurrent并发库实例

标签: javastringsemaphorethreadclass
 3670人阅读 评论(0) 收藏 举报
 分类:

Concurrent并发库底层实现主要基于AbstractQueuedSynchorizer对象,通过控制信号量,调用tryAcquire(),tryRelease()等方式实现了以下功能


1.AllenThread:Thread实例

[java] view plaincopy
  1. /** 
  2.  * @author fuweiwei.pt 
  3.  * 
  4.  */  
  5. public class AllenThread extends Thread {  
  6.     @Override  
  7.     public void run() {  
  8.         // TODO Auto-generated method stub  
  9.         System.out.println("hello allen");  
  10.     }  
  11.     public static void main(String[] args){  
  12.         for(int i=0;i<10;i++){  
  13.         Thread t=new AllenThread();  
  14.         t.start();  
  15.         }  
  16.     }  
  17. }  

 

2.BlockingQueueTest实例

[java] view plaincopy
  1. import java.io.File;  
  2. import java.util.concurrent.BlockingQueue;  
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5. import java.util.concurrent.LinkedBlockingDeque;  
  6. import java.util.concurrent.LinkedBlockingQueue;  
  7. import com.sun.org.apache.bcel.internal.generic.NEW;  
  8. public class BlockingQueueTest {  
  9.     public static File extFile = new File("");  
  10.     /** 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         // TODO Auto-generated method stub  
  15.         BlockingQueue queue = new LinkedBlockingQueue<File>(100);  
  16.         ExecutorService exe = Executors.newFixedThreadPool(5);  
  17.         exe.submit(new WriteRunnable(queue));  
  18.         for (int i = 0; i < 4; i++) {  
  19.             exe.submit(new ReadRunnable("线程"+i,queue));  
  20.         }  
  21.         exe.shutdown();  
  22.     }  
  23. }  
  24. class WriteRunnable implements Runnable {  
  25.     private BlockingQueue queue;  
  26.     public BlockingQueue getQueue() {  
  27.         return queue;  
  28.     }  
  29.     public void setQueue(BlockingQueue queue) {  
  30.         this.queue = queue;  
  31.     }  
  32.     public WriteRunnable(BlockingQueue queue) {  
  33.         this.queue = queue;  
  34.     }  
  35.     @Override  
  36.     public void run() {  
  37.         // TODO Auto-generated method stub  
  38.         try {  
  39.             writeFile(new File("d://fun"));  
  40.             writeFile(new File(""));  
  41.             // queue.put(new File("D://jboss"));  
  42.         } catch (InterruptedException e) {  
  43.             // TODO Auto-generated catch block  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47.     public void writeFile(File file) throws InterruptedException {  
  48.         if (file.isDirectory()) {  
  49.             for (File newFile : file.listFiles()) {  
  50.                 writeFile(newFile);  
  51.             }  
  52.         } else {  
  53.             queue.put(file);  
  54.             // if (file != new File("D://jboss"))  
  55.             if (file != new File(""))  
  56.                 System.out.println("队列添加:" + file.getName());  
  57.         }  
  58.     }  
  59. }  
  60. class ReadRunnable implements Runnable {  
  61.     private BlockingQueue queue;  
  62.     private String str;  
  63.     public String getStr() {  
  64.         return str;  
  65.     }  
  66.     public void setStr(String str) {  
  67.         this.str = str;  
  68.     }  
  69.     public BlockingQueue getQueue() {  
  70.         return queue;  
  71.     }  
  72.     public void setQueue(BlockingQueue queue) {  
  73.         this.queue = queue;  
  74.     }  
  75.     public ReadRunnable(String str,BlockingQueue queue) {  
  76.         this.queue = queue;  
  77.         this.str=str;  
  78.     }  
  79.     @Override  
  80.     public void run() {  
  81.         // TODO Auto-generated method stub  
  82.         try {  
  83.             while (true) {  
  84.                 Thread.sleep(1000);  
  85.                 File file = (File) queue.take();  
  86.                 // if (file.getName() .equals( new File("D://jboss").getName()))  
  87.                 // {  
  88.                 if (file.getName() == new File("").getName()) {  
  89.                     queue.put(file);  
  90.                     break;  
  91.                 } else  
  92.                     System.out.println(this.str+"从队列中取出文件:" + file.getName());  
  93.             }  
  94.         } catch (InterruptedException e) {  
  95.             // TODO Auto-generated catch block  
  96.             e.printStackTrace();  
  97.         }  
  98.     }  
  99. }  

3.CallableThread实例:可用线程池的submit()方法进行提交,同样返回一个Future对象

[java] view plaincopy
  1. import java.util.concurrent.Callable;  
  2. import java.util.concurrent.ExecutionException;  
  3. import java.util.concurrent.FutureTask;  
  4. public class CallableThread {  
  5.     public static void main(String[] args) {  
  6.         FutureTask<Integer[]> ft = new FutureTask<Integer[]>(new MyCallable(3));  
  7.         new Thread(ft).start();  
  8.         try {  
  9.             Integer[] output=(Integer[])ft.get();  
  10.             for(int i=0;i<output.length;i++)  
  11.             {  
  12.                 System.out.println(output[i]);  
  13.             }  
  14.         } catch (InterruptedException e) {  
  15.             // TODO Auto-generated catch block  
  16.             e.printStackTrace();  
  17.         } catch (ExecutionException e) {  
  18.             // TODO Auto-generated catch block  
  19.             e.printStackTrace();  
  20.         }  
  21.           
  22.     }  
  23. }  
  24. class MyCallable implements Callable<Integer[]> {  
  25.     private int max;  
  26.     public MyCallable(int i) {  
  27.         this.max = i;  
  28.     }  
  29.     @Override  
  30.     public Integer[] call() throws Exception {  
  31.         // TODO Auto-generated method stub  
  32.         Integer[] count = new Integer[max];  
  33.         for (int i = 0; i < max; i++) {  
  34.             count[i] = 10 + i + 200;  
  35.         }  
  36.         return count;  
  37.     }  
  38. }  

4.CountDownLatchTest实例

[java] view plaincopy
  1. import java.util.concurrent.CountDownLatch;  
  2. public class CountDownLatchTest {  
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         // TODO Auto-generated method stub  
  8.         CountDownLatch latch=new CountDownLatch(2);  
  9.         for(int i=0;i<3;i++)  
  10.         {  
  11.             new Thread(new HelloThread("hello "+i)).start();  
  12.             latch.countDown();  
  13.         }  
  14.         try {   
  15.             latch.await();  
  16.         } catch (InterruptedException e) {  
  17.             // TODO Auto-generated catch block  
  18.             e.printStackTrace();  
  19.         }  
  20.         System.out.println("main 主线程结束");  
  21.     }  
  22. }  

5.CyclicBarrierTest实例

[java] view plaincopy
  1. import java.util.concurrent.BrokenBarrierException;  
  2. import java.util.concurrent.CyclicBarrier;  
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5. public class CyclicBarrierTest {  
  6.     /** 
  7.      * @param args 
  8.      */  
  9.     public static void main(String[] args) {  
  10.         // TODO Auto-generated method stub  
  11.         CyclicBarrier barrier = new CyclicBarrier(3);  
  12.         ExecutorService exe = Executors.newFixedThreadPool(3);  
  13.         exe.submit(new Thread(new CyclicBarrierThread("hello", barrier)));  
  14.         exe.submit(new Thread(new CyclicBarrierThread("china", barrier)));  
  15.         exe.submit(new Thread(new CyclicBarrierThread("world", barrier)));  
  16.         exe.shutdown();  
  17.         System.out.println("CyclicBarrier Test is over");  
  18.     }  
  19. }  
  20. class CyclicBarrierThread implements Runnable {  
  21.     private String str;  
  22.     private CyclicBarrier barrier;  
  23.     public CyclicBarrier getBarrier() {  
  24.         return barrier;  
  25.     }  
  26.     public void setBarrier(CyclicBarrier barrier) {  
  27.         this.barrier = barrier;  
  28.     }  
  29.     public String getStr() {  
  30.         return str;  
  31.     }  
  32.     public void setStr(String str) {  
  33.         this.str = str;  
  34.     }  
  35.     public CyclicBarrierThread(String str, CyclicBarrier barrier) {  
  36.         this.str = str;  
  37.         this.barrier = barrier;  
  38.     }  
  39.     @Override  
  40.     public void run() {  
  41.         try {  
  42.             // TODO Auto-generated method stub  
  43.             for (int i = 0; i < 10; i++) {  
  44.                 System.out.println(i + this.str);  
  45.             }  
  46.             barrier.await();  
  47.             System.out.println(this.str+"结束Action");  
  48.         } catch (InterruptedException e) {  
  49.             // TODO Auto-generated catch block  
  50.             e.printStackTrace();  
  51.         } catch (BrokenBarrierException e) {  
  52.             // TODO Auto-generated catch block  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56. }  

6.ExecutorTest实例

[java] view plaincopy
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. public class ExecutorTest {  
  4.     /** 
  5.      * @param args 
  6.      */  
  7.     public static void main(String[] args) {  
  8.         // TODO Auto-generated method stub  
  9.         ExecutorService exe=Executors.newFixedThreadPool(2);  
  10.         for (int i = 0; i < 100; i++) {  
  11.             Runnable r=new ExecutorRunnable("this is :"+i);  
  12.             exe.submit(r);  
  13.         }  
  14.         exe.shutdown();  
  15.     }  
  16. }  
  17. class ExecutorRunnable implements Runnable{  
  18.     private String str;  
  19.     public ExecutorRunnable(String str){  
  20.         this.str=str;  
  21.     }  
  22.     @Override  
  23.     public void run() {  
  24.             //TODO Auto-generated method stub  
  25.         System.out.println(str+"输出线程为:"+Thread.currentThread().getName());  
  26.     }  
  27.     public String getStr() {  
  28.         return str;  
  29.     }  
  30.     public void setStr(String str) {  
  31.         this.str = str;  
  32.     }  
  33.       
  34.       
  35. }  

7.GameBarrier实例

[java] view plaincopy
  1. import java.util.concurrent.BrokenBarrierException;  
  2. import java.util.concurrent.CyclicBarrier;  
  3. public class GameBarrier {  
  4.     public static void main(String[] args) {  
  5.         CyclicBarrier cyclicBarrier = new CyclicBarrier(4new Runnable() {  
  6.             @Override  
  7.             public void run() {  
  8.                 // TODO Auto-generated method stub  
  9.                 System.out.println("全部已经过关 ");  
  10.             }  
  11.         });  
  12.         for (int i = 0; i < 4; i++) {  
  13.             new Thread(new Player(i, cyclicBarrier)).start();  
  14.         }  
  15.         System.out.println("测试结束");  
  16.     }  
  17. }  
  18. class Player implements Runnable {  
  19.     private CyclicBarrier cyclicBarrier;  
  20.     private int id;  
  21.     public Player(int id, CyclicBarrier cyclicBarrier) {  
  22.         this.cyclicBarrier = cyclicBarrier;  
  23.         this.id = id;  
  24.     }  
  25.     @Override  
  26.     public void run() {  
  27.         try {  
  28.             System.out.println("玩家" + id + "正在玩第一关...");  
  29.             cyclicBarrier.await();  
  30.             System.out.println("玩家" + id + "进入第二关...");  
  31.         } catch (InterruptedException e) {  
  32.             e.printStackTrace();  
  33.         } catch (BrokenBarrierException e) {  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  
  37. }  

8.MuFutureTask实例

[java] view plaincopy
  1. import java.util.concurrent.Callable;  
  2. import java.util.concurrent.CountDownLatch;  
  3. import java.util.concurrent.ExecutionException;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.Future;  
  7. public class MyFutureTask {  
  8.     /** 
  9.      * @param args 
  10.      * @throws InterruptedException  
  11.      * @throws ExecutionException 
  12.      * @throws InterruptedException 
  13.      * @throws ExecutionException  
  14.      */  
  15.     public static void main(String[] args) throws InterruptedException, ExecutionException {  
  16.         // TODO Auto-generated method stub  
  17.         /* 
  18.          * try { CallThread thread = new CallThread(3); FutureTask<int[]> 
  19.          * futureTask = new FutureTask<int[]>(thread); Thread t = new 
  20.          * Thread(futureTask); t.start(); Thread.sleep(2000); String a = null; 
  21.          * MyThreadTest mt = new MyThreadTest("hello more"); Thread t2 = new 
  22.          * Thread(mt); t2.start(); System.out.println(mt.getStr()); // 
  23.          * 先做其它事情,再做FutureTas的东西 System.out.println("是否提前结束"); 
  24.          *  
  25.          * if (futureTask.isDone()) { int[] count = futureTask.get(); 
  26.          * System.out.println(count[0]); } 
  27.          *  } catch (Exception e) { // TODO: handle exception 
  28.          * System.out.println("error"); } 
  29.          */  
  30. //      CountDownLatch latch = new CountDownLatch(10);  
  31. //      for (int i = 0; i < args.length; i++) {  
  32.               
  33.             // MyThreadTest myRunnable=new MyThreadTest("aaa");  
  34.               
  35. //          t.sleep(1000);  
  36. //          latch.countDown();  
  37. //      }  
  38. //      try {  
  39. //          latch.await();  
  40. //      } catch (InterruptedException e) {  
  41. //          // TODO Auto-generated catch block  
  42. //          e.printStackTrace();  
  43. //      }  
  44.           
  45. //      System.out.println(myRunnable.getStr());  
  46.         //sayHello();  
  47.         final ExecutorService exe=Executors.newFixedThreadPool(3);  
  48.         Callable<String> call=new Callable<String>(){  
  49.             public String call() throws InterruptedException {  
  50. //              Thread.sleep(2000);  
  51.                 return "Thread is finished";  
  52.             }  
  53.         };  
  54.         Future<String> task=exe.submit(call);  
  55.         String obj=task.get();  
  56.         System.out.println(obj+"进程结束");  
  57.         System.out.println("总进程结束");  
  58.         exe.shutdown();  
  59.     }  
  60.     private static void sayHello(){  
  61.         MyThreadTest myRunnable = new MyThreadTest("aaa");  
  62.         Thread t = new Thread(myRunnable);  
  63.         t.start();  
  64.         String a=myRunnable.getStr();//此时应该输出allen;aaa  
  65.         System.out.println(a);  
  66.         System.out.println("my world");  
  67.     }  
  68. }  
  69. class MyThreadTest implements Runnable {  
  70.     private String str;  
  71.     private CountDownLatch latch;  
  72.     // public MyThreadTest(String str) {  
  73.     public MyThreadTest(String str) {  
  74.         this.str = str;  
  75.         this.latch = latch;  
  76.     }  
  77.     public void run() {  
  78.         // TODO Auto-generated method stub  
  79.         this.setStr("allen"+str);  
  80. //      addString(str);  
  81.     }  
  82.     public void addString(String str) {  
  83.         this.str = "allen:" + str;  
  84.     }  
  85.     public String getStr() {  
  86.         return str;  
  87.     }  
  88.     public void setStr(String str) {  
  89.         this.str = str;  
  90.     }  
  91. }  

9.SemaphoreTest实例

[java] view plaincopy
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.Semaphore;  
  4. public class SemaphoreTest {  
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         // TODO Auto-generated method stub  
  10.         ExecutorService exe=Executors.newCachedThreadPool();  
  11.         Semaphore semp=new Semaphore(5);  
  12.         for (int i = 0; i < 20; i++) {  
  13.             exe.execute(new SemaphoreRunnable("线程"+i,semp));  
  14.         }  
  15.         exe.shutdown();  
  16.     }  
  17. }  
  18. class SemaphoreRunnable implements Runnable{  
  19.     private String string;  
  20.     private Semaphore semp;  
  21.     public Semaphore getSemp() {  
  22.         return semp;  
  23.     }  
  24.     public void setSemp(Semaphore semp) {  
  25.         this.semp = semp;  
  26.     }  
  27.     public String getString() {  
  28.         return string;  
  29.     }  
  30.     public void setString(String string) {  
  31.         this.string = string;  
  32.     }  
  33.     public SemaphoreRunnable(String string,Semaphore semp){  
  34.         this.semp=semp;  
  35.         this.string=string;  
  36.     }  
  37.     @Override  
  38.     public void run() {  
  39.         // TODO Auto-generated method stub  
  40.         try {  
  41.             semp.acquire();  
  42.             System.out.println("线程"+this.string+"开始处理对象");  
  43.             semp.release();  
  44.         } catch (InterruptedException e) {  
  45.             // TODO Auto-generated catch block  
  46.             e.printStackTrace();  
  47.         }  
  48.           
  49.     }  
  50.       
  51. }  

10.TestCompletionService实例

[java] view plaincopy
  1. import java.util.concurrent.Callable;  
  2. import java.util.concurrent.CompletionService;  
  3. import java.util.concurrent.ExecutionException;  
  4. import java.util.concurrent.ExecutorCompletionService;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.Future;  
  8. public class TestCompletionService {  
  9.     public static void main(String[] args) throws InterruptedException,  
  10.             ExecutionException {  
  11.         ExecutorService exec = Executors.newFixedThreadPool(10);  
  12.         CompletionService serv = new ExecutorCompletionService(exec);  
  13.         for (int index = 0; index < 5; index++) {  
  14.             final int NO = index;  
  15.             Callable downImg = new Callable() {  
  16.                 public String call() throws Exception {  
  17.                     Thread.sleep((long) (Math.random() * 10000));  
  18.                     return "Downloaded Image " + NO;  
  19.                 }  
  20.             };  
  21.             serv.submit(downImg);  
  22.         }  
  23.         Thread.sleep(1000 * 2);  
  24.         System.out.println("Show web content");  
  25.         for (int index = 0; index < 5; index++) {  
  26.             Future task = serv.take();  
  27.             String img = (String)task.get();  
  28.             System.out.println(img);  
  29.         }  
  30.         System.out.println("End");  
  31.         // 关闭线程池  
  32.         exec.shutdown();  
  33.     }  
  34. }

0 0
原创粉丝点击