How to realize two threads running alternately in Java
Xiaobian to share with you how to achieve two threads running alternately in Java, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
Received a teacher's topic, let me prepare two processes, in turn to achieve the output of the following information
For example:
Thread A prints the letter a , thread B prints the number 1.
Thread A prints letter b , thread B prints number 2
Thread A prints the letter c , thread B prints the number 3.
Thread A prints the letter d , thread B prints the number 4.
。。。
26 letters and 26 numbers.
The output effect is:
a1b2c3... z26
The following is a list of the ways in which this can be done:
1. The multithreaded wait method will be used
2. With an external variable
package com.java265.other;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'); 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