Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize two threads running alternately in Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report