多线程中几个特殊的类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程中几个特殊的类相关的知识,希望对你有一定的参考价值。

1、FutureTask

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.*;
 4 
 5 /**
 6  * Created by Administrator on 2017/5/17.
 7  */
 8 public class UseFuture implements Callable<String> {
 9 
10     private String para;
11 
12     public UseFuture(String para){
13         this.para = para;
14     }
15 
16     /**
17      * 这里是真实的业务逻辑,其执行可能很慢
18      */
19     @Override
20     public String call() throws Exception {
21         //模拟执行耗时
22         Thread.sleep(5000);
23         String result = this.para + "处理完成";
24         return result;
25     }
26 
27     //主控制函数
28     public static void main(String[] args) throws Exception {
29         String queryStr = "query";
30         //构造FutureTask,并且传入需要真正进行业务逻辑处理的类,该类一定是实现了Callable接口的类
31         FutureTask<String> future = new FutureTask<String>(new UseFuture(queryStr));
32 
33         FutureTask<String> future2 = new FutureTask<String>(new UseFuture(queryStr));
34         //创建一个固定线程的线程池且线程数为1,
35         ExecutorService executor = Executors.newFixedThreadPool(2);
36         //这里提交任务future,则开启线程执行RealData的call()方法执行
37         //submit和execute的区别: 第一点是submit可以传入实现Callable接口的实例对象, 第二点是submit方法有返回值
38 
39         Future f1 = executor.submit(future);        //单独启动一个线程去执行的
40         Future f2 = executor.submit(future2);
41         System.out.println("请求完毕");
42 
43         try {
44             //这里可以做额外的数据操作,也就是主程序执行其他业务逻辑
45             System.out.println("处理实际的业务逻辑...");
46             Thread.sleep(1000);
47         } catch (Exception e) {
48             e.printStackTrace();
49         }
50         //调用获取数据方法,如果call()方法没有执行完成,则依然会进行等待
51         System.out.println("数据:" + future.get());
52         System.out.println("数据:" + future2.get());
53 
54         executor.shutdown();
55     }
56 
57 
58 }

2、CyclicBarrier

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.io.IOException;
 4 import java.util.Random;
 5 import java.util.concurrent.BrokenBarrierException;
 6 import java.util.concurrent.CyclicBarrier;
 7 import java.util.concurrent.ExecutorService;
 8 import java.util.concurrent.Executors;
 9 
10 /**
11  * Created by Administrator on 2017/5/17.
12  */
13 public class UseCyclicBarrier {
14 
15     static class Runner implements Runnable {
16         private CyclicBarrier barrier;
17         private String name;
18 
19         public Runner(CyclicBarrier barrier, String name) {
20             this.barrier = barrier;
21             this.name = name;
22         }
23         @Override
24         public void run() {
25             try {
26                 Thread.sleep(1000 * (new Random()).nextInt(5));
27                 System.out.println(name + " 准备OK.");
28                 barrier.await();
29             } catch (InterruptedException e) {
30                 e.printStackTrace();
31             } catch (BrokenBarrierException e) {
32                 e.printStackTrace();
33             }
34             System.out.println(name + " Go!!");
35         }
36     }
37 
38     public static void main(String[] args) throws IOException, InterruptedException {
39         CyclicBarrier barrier = new CyclicBarrier(3);  // 3
40         ExecutorService executor = Executors.newFixedThreadPool(3);
41 
42         executor.submit(new Thread(new Runner(barrier, "zhangsan")));
43         executor.submit(new Thread(new Runner(barrier, "lisi")));
44         executor.submit(new Thread(new Runner(barrier, "wangwu")));
45 
46         executor.shutdown();
47     }
48 
49 }

3、CountDownLatch

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 
 5 /**
 6  * Created by Administrator on 2017/5/17.
 7  */
 8 public class UseCountDownLatch {
 9 
10     public static void main(String[] args) {
11 
12         final CountDownLatch countDown = new CountDownLatch(2);
13 
14         Thread t1 = new Thread(new Runnable() {
15             @Override
16             public void run() {
17                 try {
18                     System.out.println("进入线程t1" + "等待其他线程处理完成...");
19                     countDown.await();
20                     System.out.println("t1线程继续执行...");
21                 } catch (InterruptedException e) {
22                     e.printStackTrace();
23                 }
24             }
25         },"t1");
26 
27         Thread t2 = new Thread(new Runnable() {
28             @Override
29             public void run() {
30                 try {
31                     System.out.println("t2线程进行初始化操作...");
32                     Thread.sleep(3000);
33                     System.out.println("t2线程初始化完毕,通知t1线程继续...");
34                     countDown.countDown();
35                 } catch (InterruptedException e) {
36                     e.printStackTrace();
37                 }
38             }
39         });
40         Thread t3 = new Thread(new Runnable() {
41             @Override
42             public void run() {
43                 try {
44                     System.out.println("t3线程进行初始化操作...");
45                     Thread.sleep(4000);
46                     System.out.println("t3线程初始化完毕,通知t1线程继续...");
47                     countDown.countDown();
48                 } catch (InterruptedException e) {
49                     e.printStackTrace();
50                 }
51             }
52         });
53 
54         t1.start();
55         t2.start();
56         t3.start();
57     }
58 }

4、Semaphore

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.Semaphore;
 6 
 7 /**
 8  * Created by Administrator on 2017/5/17.
 9  */
10 public class UseSemaphore {
11 
12     public static void main(String[] args) {
13         // 线程池
14         ExecutorService exec = Executors.newCachedThreadPool();
15         // 只能5个线程同时访问
16         final Semaphore semp = new Semaphore(5);
17         // 模拟20个客户端访问
18         for (int index = 0; index < 20; index++) {
19             final int NO = index;
20             Runnable run = new Runnable() {
21                 public void run() {
22                     try {
23                         // 获取许可
24                         semp.acquire();
25                         System.out.println("Accessing: " + NO);
26                         //模拟实际业务逻辑
27                         Thread.sleep((long) (Math.random() * 10000));
28                         // 访问完后,释放
29                         semp.release();
30                     } catch (InterruptedException e) {
31                     }
32                 }
33             };
34             exec.execute(run);
35         }
36 
37         try {
38             Thread.sleep(10);
39         } catch (InterruptedException e) {
40             e.printStackTrace();
41         }
42         //System.out.println(semp.getQueueLength());
43         // 退出线程池
44         exec.shutdown();
45     }
46 }

 

以上是关于多线程中几个特殊的类的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 中几个有用的特殊函数

java多线程学习之——多线程中几种释放锁和不释放锁的操作

python类中几个特殊方法

linux shell 脚本中几个特殊参数含义

linux中几个重要的守护线程

java 中几种常用数据结构