Today, the author received a question from the teacher, asking me to prepare two processes and output the following information in turn.
like:
Thread A prints letter a, thread B prints number 1
Thread A prints letter b, thread B prints number 2
Thread A prints letter c, thread B prints number 3
Thread A prints letter d, thread B prints number 4
。。。
Print 26 letters and 26 numbers in turn
, the output effect is:
a1b2c3...z26
The author will show the specific implementation ideas below:
1. Will use the multi-threaded wait method
2. With an external variable
package com.; public class Test6 { /* * Two threads One thread output a b c d e f One thread output 1 2 3 4 5 Cross-output 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'); (t); i++; try { (); } catch (InterruptedException e) { (); } flag = false; (); } } } }); t2 = new Thread(() -> { for (int i = 1; i <= 26;) { synchronized (o) { if (flag) { (i); i++; try { (); } catch (InterruptedException e) { (); } } flag = true; (); } } }); (); (); } }
Reference information:
/JavaMianJing/202112/
This is the article about implementing the process of two threads alternately running in Java. For more related content on alternately running of Java threads, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!