使多个线程循环输出0-99-0-99

直接上代码,后面我也有一个问题,关于对象的notifyAll或者notify或者single或者singleAll,唤醒线程是顺序唤醒吗,我这里都是顺序输出了

关于公平与非公平锁的问题?唤醒是公平的???又没有大佬帮助解答!

复制代码
 1 import java.util.concurrent.LinkedBlockingQueue;
 2 import java.util.concurrent.ThreadPoolExecutor;
 3 import java.util.concurrent.TimeUnit;
 4 import java.util.concurrent.locks.Condition;
 5 import java.util.concurrent.locks.Lock;
 6 import java.util.concurrent.locks.ReentrantLock;
 7 
 8 /**
 9  * 使用lock对象,使多个线程循环输出0-99-0-99
10  */
11 public class AandBforTOthreadLock {
12     private static Lock lock=new ReentrantLock();
13     private static Condition single=lock.newCondition();
14     static class A implements Runnable{
15         private int i=0;
16         public A(int i){
17             this.i=i;
18         }
19         @Override
20         public void run() {
21             try {
22                 lock.lock();
23                 while (true){
24                     System.out.println(i);
25                     single.await();
26                     single.signal();
27                 }
28             }catch (Exception e){
29                 e.printStackTrace();
30             }finally {
31                 lock.unlock();
32             }
33         }
34     }
35     static class B implements Runnable{
36         @Override
37         public void run() {
38             try {
39                 lock.lock();
40                 while (true){
41                     System.out.println("99");
42                     single.signalAll();
43                     single.await();
44                 }
45             }catch (Exception e){
46                 e.printStackTrace();
47             }finally {
48                 lock.unlock();
49             }
50         }
51     }
52 
53     public static void main(String[] args) throws InterruptedException {
54         ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(100,100,0L, TimeUnit.MILLISECONDS,
55                 new LinkedBlockingQueue<Runnable>());
56         for (int i=0;i<99;i++){
57             threadPoolExecutor.execute(new A(i));
58             Thread.sleep(3l);
59         }
60         Thread.sleep(10000l);
61         threadPoolExecutor.execute(new B());
62     }
63 
64 }
输出:

……

 

 
 

转载于:https://www.cnblogs.com/qfxydtk/p/8728840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值