今天筆者收到老師的一個題目,讓我准備兩個流程,依次實現輸出以下信息
如:
線程A 打印 字母a ,線程B 打印數字1
線程A 打印 字母b ,線程B 打印數字2
線程A 打印 字母c ,線程B 打印數字3
線程A 打印 字母d ,線程B 打印數字4
。。。
依次打印完畢26個字母和26個數字
,輸出效果為:
a1b2c3...z26
下文筆者就將具體的實現思路展示如下:
1.將借助多線程的wait方法
2.借助一個外部變量
package com.java265.other; public class Test6 { /* * 兩個線程 一個線程輸出 a b c d e f 一個線程輸出 1 2 3 4 5 交叉輸出 a 1 b 2 c 3 */ static boolean flag = false; public static void main(String[] args) { Object o = new Object(); Thread t1, t2; t1 = new Thread(() -> { for (int i = 0; i < 26; ) { synchronized (o) { if (!flag) { char t = (char) (i + (int) 'a'); System.out.print(t); i++; try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } flag = false; o.notifyAll(); } } } }); t2 = new Thread(() -> { for (int i = 1; i <= 26;) { synchronized (o) { if (flag) { System.out.print(i); i++; try { o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } flag = true; o.notifyAll(); } } }); t1.start(); t2.start(); } }
