Java multi-threaded learning note (2)

zhaozj2021-02-16  46

Java multi-threaded learning note (2)

Author: cultivate (innocent) Time: 2003.6.21

Fourth, Java's waiting notice mechanism is sometimes, we need to share certain resources in a few or more threads. For example, the actual situation of the consumer is always available in this pair of practices, and consumers can consume after producing the product; if they are in the parent - child relationship, they always have Father, then you can have a son. However, we get the situation in the case where there is no introduction to the notification mechanism, is often wrong. Here I introduce the producer of "Working with Threads" - Consumers - consumer example: / * ========================== ============================================================================================================================================================================================================= ======== * file: threadDemo07.java * Description: Producer - Consumer * Note: Some of the comments are my own understanding * =========== ============================================================================================================================================================================================================= ====================== * /

// Shared data object class sharedata {private char C; public void setsharechar (this.c = C;} public char GetsharChar () {returnim;}} // producers thread Class Producer Extends thread {Private Sharedata S; PRODATA S) {this.s = S;} public void Run () {for (char CH = 'a'; ch <= 'z'; ch ) {TRY {thread.sleep (( INT.random () * 4000);} catch (interruptedException e) {} // produces s.setsharChar (CH); System.out.Println (CH "Producter by Producer.");}}} // Consumer Thread Class Consumer Extends Thread {Private Sharedata S; Consumer (Sharedata s) {this.s = s;} public void run () {char ch; do {Try {thread.sleep ((int) math.random () * 4000);} catch (interruptedException e) {} // spending CH = s.getsharChar (); system.out.println (CH "consumer by consumer.");} While (ch! = 'Z'); }} Class test {public static void main (string argv []) {sharedata s = new sharedata (); new consumer (s) .start (); new product (s) .start (); }

In the above programs, the relationship between producers and consumers is simulated. The producer continuously produces shared data from A-Z in a loop, while consumers constantly consume the share of A-Z produced by producers. . We have already said that in this pair, we must have producers to produce, in order to have consumers. But if you run the above procedure, the result has appeared before the producer is not produced, the consumption has begun to consume or produce the producer but cannot be consumed by consumers. In order to solve this problem, the Wait / Notify mechanism is introduced as follows: 1. Inform consumers waiting before the producer is not produced; after the producer production, the consumer consumption will be notified immediately. 2. After consumers consume, notify that the producer has consumed it, it needs to be produced. The above examples are modified (derived from "a powerful function"):

/ * ================================================================================================================================================================ ============================================ * file: threadDemo08.java * Description: Producer - Consumer * Note: Some of the comments are my own understanding * ====================================================================================================================================== ======================================================== * / Class Sharedata {Private Char C; // Notification Variable Private Boolean Writeable = true;

/ / -------------------------------------------------------------------------------------------- ------------------------- // Need to pay attention to: When calling the wait () method, you need to put it in a synchronization segment. Otherwise, // "java.lang.illegalmonitorstateException: Current Thread Not Owner" will appear. / / -------------------------------------------------------------------------------------------- ------------------------- Public synchronized void setsharechar (char c) {if (! Writeable) {try {// unspecified Wait () } Catch (interruptedException e) {}} this.c = c; // Tagging has been produced by Writeable = false; // Notifying consumers have been produced, can consume notify ();} public synchronized char GetsharChar () {ix (Writeable ) {Try {// unsuccessful Wait ();} catch (interruptedException e) {}} // Tags have been consumed Writeable = true; // Notification requires production notify (); returnim;}}}}

// Producer Thread Class Producer Extends Thread {Private Sharedata S; Producter (Sharedata S) {this.s = S;} Public Void Run () {for (CHAR CH = 'A'; CH <= 'Z'; CH ) {Try {thread.sleep ((int) math.random () * 400);} catch (interruptedException e) {} s.setsharechar (ch); system.out.println (CH "Producter by Producter.") ;}}} // Consumer Thread Class Consumer Extends Thread {Private Sharedata S; Consumer (Sharedata S) {this.s = S;} public void Run () {char ch; do {Try {thread.sleep ((int) ) Math.random () * 400);} catch (interruptexception e) {} ch = s.getsharechar (); system.out.println (ch "consumer by consumer. **);} while (ch! = 'Z'); }}

Class test {public static void main (string argv []) {sharedata s = new sharedata (); new consumer (s) .start (); new product (s) .start ();}}

In the above programs, a notification variable is set. Each time you test the notification variable before the manufacturer production and consumer consumption, check whether you can produce or consume. The start setting of the notification variable is true, indicating that it has not yet been produced, at this time, the consumer needs to consume, and the notification variable is modified, and the notify () issued a notification. At this time, since the producer gets notified, the first product is produced, and the notification variable is produced, and notifications will be issued to the consumer. At this time, if the producer wants to continue to produce, but because the notification variable is false, I know that the consumer has not yet been produced, so calling Wait () into the waiting state. Therefore, the final result is that the producer will notify consumers to consume every one; consumers will notify the producer to produce one, so there will be no production or overproduction.

V. Thread interruptions In many cases, we need to regulate another thread in a thread. At this time, we will use thread interrupts. In the simplest, it may be said that it is equivalent to the suspension in the player. When the first presin first presses, the player stops playing, and then press the pause again, continue to replay from the place you just stopped. In Java, this pause button is an interrupt () method. When the Interrupt () method is called for the first time, the thread is interrupted; when the interrupt () method is called again, the thread continues to run until termination. Here, the program is referred to in the article "Working with Thread", but in order to easier to see the interrupt, I have improved on the basis of the original program, the program is as follows:

/ * ================================================================================================================================================================ =================================== * file: threadDemo09.java * Description: Thread interrupt * == ============================================================================================================================================================================================================= ======================================================================================================================= THDOTHER = THDOTHER;} public void run () {system.out.println (GetName () "Run ..."); int sleeptime = (int) (math.random () * 10000); system.out.println (GetName () "Sleep" SleepTime "Mixi."); try {thread.sleep (sleeptime);} catch (interruptedException e) {} system.out.println (getName () "awakening, will be interrupted thread B. "); // Interrupt Thread B, thread B suspend run trdother.interrupt ();}}

Class threadb extends thread {int count = 0; public void run () {system.out.println (getName () "Run ..."); while (! this.isterrupted ()) {system.out.println GetName () "run" count ); try {thread.sleep (10);} catch (interruptedExcection e) {Int sleeptime = (int) (math.random () * 10000); system.out.println GetName () "Sleep" SleepTime "in milliseconds. Run immediately until the end."); try {thread.sleep (sleeptime);} catch (interruptedException m) {} system.out.println (GetName () "I have awakened, run ..."); // Reset the tag, continue to run this.interrupt ();}} system.out.println (GetName () "termination.");}} Class test {PUBLIC Static void main (string argv []) {threadb twth threadb (); thredb.setname ("threadb"); Threada THDA = New Threada (THDB); THDA.SetName ("Threada"); THDB.Start () Thda.start ();}}

Run the above programs, you can clearly see the process of interrupt. First, thread b start running, then running thread a, after the thread A sleep, call the interrupt () method to interrupt the thread B, which may be sleeping, then take out an interruptedException exception, execute the statement, in order to Clearly see the interrupt recovery of the thread, I added a sleep after INTERRUPTEDException, after the end of the sleep, the thread b called its own interrupt () method to restore the interrupt, and ISINTERRUPT () returns TRUE, thread exits.

For more thread groups and related more detailed information, please refer to "Threading IN Java" in "Thinking in Java".

转载请注明原文地址:https://www.9cbs.com/read-24356.html

New Post(0)