线程交替输出A1B2C3.........Z26
为了完成作业。。。。直接贴代码,复制可直接运行
第一版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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(); } |
第三种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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(); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!