Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the Communication of Java Thread

Shulou Source: shulou.com Published: 2022-06-01 04:25:31 09月17日 Update

This article mainly introduces the relevant knowledge of how to achieve Java thread communication, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Java thread communication article. Let's take a look at it.

/ / collaboration model-producer-consumer implementation method-semaphore method / / with the help of flag bits-flag is the key public class ThreadCopperator02 {public static void main (String [] args) {Tv tv=new Tv (); new Watcher (tv). Start (); new Player (tv). Start ();}} / Consumer audience class Watcher extends Thread {Tv tv;public Watcher (Tv tv) {this.tv = tv } @ Override public void run () {for (int I = 0; I < 20; iTunes +) {tv.watch ();} / / producer actor class Player extends Thread {Tv tv;public Player (Tv tv) {this.tv = tv;} @ Override public void run () {for (int I = 0; I < 20; iTunes +) {if (I% 2% weird 0) {this.tv.play } else {this.tv.play ("standing white");} / / the same resource TV class Tv {String voice;// signal / / if it is true, the actor performs, the audience waits / / if it is false, the audience watches, the actor waits for boolean flag=true Public synchronized void play (String voice) {/ / actors wait for if (! flag) {try {this.wait (); / / wait will release lock} catch (InterruptedException e) {e.printStackTrace ();}} / / perform System.out.println ("performed" + voice); this.voice=voice / / wakes up the wait of the thread of watch to execute the following program, thus outputting "heard." This.notifyAll (); / / toggle the flag this.thread has to wait because there is a lock, public synchronized void watch () one by one {/ / viewers wait for if (flag) {try {this.wait ();} catch (InterruptedException e) {e.printStackTrace () }} / / watching System.out.println ("heard" + voice); / / wakes up the wait of the thread of play to execute the following program, thus outputting the "show." This.notifyAll (); / / toggle the flag this.communication implementation for Java threads;}} this is the end of the article on "how to implement Java thread communication". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to realize the communication of Java threads". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Tags: Threads communications actors audiences performances logos knowledge signals signals content consumers producers programs articles facets switching consumption production output value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft OPPO Reno Linux vpn Shulou Technology