Java Note Seven. Inter-thread communication and thread life control

Source: Internet
Author: User

inter-thread communication and thread life controlOne, thread communication methodJava is through the object class wait, notify, notifyall These methods to implement the process key communication. Because all classes inherit from object, these methods can be used directly in any class. wait: Tells the current thread to discard the monitor and go to sleep, knowing that other threads have entered the same monitor and called notify;Notify: Wakes the first thread in the same object monitor that calls wait. Used for similar restaurants having an empty space to inform all customers waiting for the first place to be seated;Notifyall: Wakes all threads that call wait in the same object monitor , and the thread with the highest priority is awakened and executed first, for a class that is similar to an irregular course finally, after the admission is completed, all the students are informed of the attendance. Note: This is called the same object monitor, which refers to the synchronized (object) of inter-thread communicationObjects in the same object.
II. Producer-consumer model1. Introductionproducer Producer.java: When the database data is read by the consumer, the data is written to a database;consumer Customer.java: When the database has data and the producer writes, the data is read;Database Data.java: A class that provides two methods for reading and writing, and for thread synchronization and the same object monitorMain thread Threadcommunication.java: Creates two threads, the thread shares the same resource data.2. Functional Source Codeimplementation: Producer thread to hold data, consumer thread to go once, conversely, producer also must wait until consumer take out to store new data. (1) Data.java
public class data{String name = "JJ Lin";//Initialize data string sex= "male"; Boolean isnull=false;//Identify public synchronized void put (St Ring name,string Sex)  //Deposit data method {  if (isNull)//When the data class is not empty when the thread that gets the flag enters the wait state   try {Wait ();} catch ( Interruptedexception E1) {e1.printstacktrace ();}  This.name=name;  Try{thread.sleep (100);} catch (Exception e) {e.printstacktrace ();}  This.sex=sex;  Isnull=true;  Notify (); The public synchronized Void get ()//reads the data method {  if (!isnull)//When the data has not been written to completion when the thread that gets the flag enters the wait state of the   try {Wait ();} catch ( Interruptedexception E1) {e1.printstacktrace ();}  System.out.println (name+ ":" +sex);  Isnull=false;  

(2)Producer.java
public class Producer implements runnable{data data=null, public Producer (data data)//constructor method {  This.data=data;} public void Run () {  int i=0;  while (true)  {   if (i==0)   {    data.put ("吴倩", "female");   }   else   {    data.put ("JJ Lin", "male");   }   i= (i+1)%2;  }}

(3)Customer.java //Consumer class
Class Customer implements runnable{data data=null; public customer (data data) {  this.data=data;} public void Run () { While  (true)  {   data.get ();  } }}

(4)Threadcommunication.java //Main class
public class threadcommunication{public static void Main (string[] args) {  data data = new data ();  New Thread (data). Start ();//producer Thread  new Thread (new Customer (data)). Start ();//Consumer Thread}}
Effect Demo :
Summary: Wait, notify, Notifyall these three methods can only be called in the Synchronized method, that is, regardless of whether a thread invokes a wait or Notify method of an object, the thread must first obtain the lock flag for that object. In this way, notify can only wake up the thread that calls wait in the same object monitor, and with multiple object monitors we can group multiple wait and notify cases, and wait in the same group can only be woken up by notify in the same group.
three, the control of thread life
1. Running a threada thread is generated from the Start method we call to enter the runnable state, that can be scheduled to run state, and does not really start to run, the scheduler can assign the CPU to it, and actually run the program code. While the thread is running, there are a couple of possible whereabouts:(1) do not encounter any barrier, the completion of the operation until the end, that is, the run () method is completed;(2) The scheduler allocates the CPU to other threads, and the thread becomes runnable state;(3) Request lock flag, but not get, this time it waits for the object lock flag, obtains the lock flag to enter the runnable state to begin to run;(4) When the Wait method is encountered, he will be placed in the waiting pool to wait until the Notify () or interrupt () method executes, and it will not wake up or interrupt to start waiting for the object lock flag until the lock flag enters the runnable state to continue execution. 2. Controlling Thread LifeThere are many ways to control the thread life cycle, such as: Suspend method, resume method, and stop method. However, it is generally not recommended to use these three methods, where suspend and resume are not recommended because:(1) can lead to the occurrence of deadlock;(2) It allows one thread to directly control which thread by directly controlling the code of another thread. In addition, although stop can avoid deadlocks, but it brings additional shortcomings, if a thread is operating a shared data segment, the operation process is not completed stop, it will lead to data integrity. Here we describe a method---setting the identity to control the thread's life cycle:Threadrunnable.java
public class Threadrunnable implements runnable{Boolean stopflag=true;//define an identity//stop thread method public void Stopme () {  Stopf Lag=false; }//run method public void run () {while   (Stopflag)   {    System.out.println (Thread.CurrentThread (). GetName () + ' is Running ");   } }}


Threadlife.java
public class threadlife{public static void Main (string[] args) {  threadrunnable runnable = new threadrunnable ();  New Thread (runnable). Start ();  for (int i=0;i<100;i++)  {     if (i==50)//When I is accumulated to 50 o'clock, end child thread     {       runnable.stopme ();     }     System.out.println ("Mainthread is Running");  } }}


Effect Demo: When I accumulates to 50 o'clock, the child thread ends.

Java Note Seven. Inter-thread communication and thread life control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.