使多个线程循环输出0-99-0-99
生活随笔
收集整理的這篇文章主要介紹了
使多个线程循环输出0-99-0-99
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
直接上代碼,后面我也有一個(gè)問題,關(guān)于對(duì)象的notifyAll或者notify或者single或者singleAll,喚醒線程是順序喚醒嗎,我這里都是順序輸出了
關(guān)于公平與非公平鎖的問題?喚醒是公平的???又沒有大佬幫助解答!
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對(duì)象,使多個(gè)線程循環(huán)輸出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 }輸出:
……
?
轉(zhuǎn)載于:https://www.cnblogs.com/qfxydtk/p/8728840.html
總結(jié)
以上是生活随笔為你收集整理的使多个线程循环输出0-99-0-99的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA 房屋出租系统(韩顺平)
- 下一篇: Java完全自学手册,你要悄悄努力,然后