线程交替输出A1B2C3.........Z26
作者:互联网
为了完成作业。。。。直接贴代码,复制可直接运行
第一版本
public static void main(String[] args){ Object o=new Object(); Thread t1=new Thread(()->{ synchronized (o){ //wait 必须在有锁的情况下使用 for (int i=0;i<26;i++){ System.out.print((char) (i + 'A')); o.notify(); //唤醒其他线程 try { o.wait(); //自身等待 } catch (InterruptedException e) { e.printStackTrace(); } } o.notify(); //必不可少,不然不会结束 } }); Thread t2=new Thread(()->{ synchronized (o){ for (int i=1;i<=26;i++){ System.out.print(i); o.notify(); try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } o.notify(); } }); t1.start(); t2.start(); }
经过数次尝试,会出现1A2B3C 的情况;
第二版本
public static void main(String[] args){ Object o=new Object(); CountDownLatch countDownLatch=new CountDownLatch(1); //门闩 1表示等待的数量 Thread t1=new Thread(()->{ countDownLatch.countDown(); //唤醒 把countDownLatch的值减1,减到0,就唤醒所有等待在这个countDownLatch上的线程 synchronized (o){ for (int i=0;i<26;i++){ System.out.print((char) (i + 'A')); o.notify(); try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } o.notify(); } }); Thread t2=new Thread(()->{ try { countDownLatch.await();//进入等待状态 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o){ for (int i=1;i<=26;i++){ System.out.print(i); o.notify(); try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } o.notify(); } }); t1.start(); t2.start(); }
第三种
public static void main(String[] args) { t1 = new Thread(() -> { for (int i = 0; i < 26; i++) { System.out.print((char) (i + 'A')); LockSupport.unpark(t2); //唤醒t2 LockSupport.park();//暂停当前线程 } }); t2 = new Thread(() -> { for (int i = 1; i <= 26; i++) { LockSupport.park(); //这个一定要在打印前暂停 System.out.print(i); LockSupport.unpark(t1); } }); t1.start(); t2.start(); }
TRANSLATE with x English TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back
标签:Z26,synchronized,Thread,int,Object,A1B2C3,线程,countDownLatch,new 来源: https://www.cnblogs.com/count0/p/16698090.html