JAVA 11 (multithreading)

Source: Internet
Author: User
Tags ticket

Inter-thread communication, in fact, is that multiple threads are operating the same resource, but the action action is different. The    Sync code block uses the same lock.  public class Test{ public static void Main (String args [])  {  res r = new Res ();  Input in = new Input (r);  output out = new Output (r);  thread T1 = new Thread (in);  thread T2 =new thread (out);  t1. Start ();  T2.start ();  }} class res{ string name; string sex;}  class Input implements Runnable{ res R;   input (Res r)  {  THIS.R = R; } public void Run ()  {  Boolean B = true;  while (true)   {   synchronized (r)    {  & Nbsp;if (b)    {    r.name= "Mike";    r.sex= "man";    b=false;   }    else   {    r.name= "Lili";    r.sex= "female female female";    b=true;   }    } } }} class Output implements Runnable{ res R; output (Res R)  {  This.r=r; } public VOID run ()  {  while (true)   {   synchronized (r)    {   system.out.println ( R.name+ "..." +r.sex);   } } }}  The code will print the duplicate of the same person, using the direct communication modification of the thread, giving a token in res.   wait for wake-up mechanism    The non-static synchronization function uses the lock when this. The lock-time class name used by the static synchronization function. Synchronize the code block with the lock arbitrary. Self-setting   wait ()  : Format try{} catch () {}notify ()  notifyall ()   Three methods inherit from the object class, The latter two methods must have the object's monitor to be able to use (that is, the lock in sync, which must be used in synchronization)   is used in synchronization because the thread that holds the monitor (lock) is operated on, so it is used in synchronization, because there is only a lock in the synchronization.   Why do threading methods have to be defined in object, because these methods must indicate the locks held by the thread they are operating on while manipulating the threads in the synchronization, and only the waiting thread of the same lock can be awakened by the same lock notify (), You cannot wake a thread in a different way. That is, the wait and wake must be the same lock, and the lock can be any object, so the method that can be called by any object is defined in the Obj class.   public class Test{ public static void Main (String args [])  {  res r = new Res ();  Input in = new Input (r);  output out = new Output (r);  thread T1 = new Thread (in);  thread T2 =new thread (out); &nbs P T1.start ();  t2.start ();  }} class res{ string name; string Sex; boolean flag = false;}  class Input implements Runnable{ res R;   input (Res r)  {  THIS.R = R; } public void Run ()  {  Boolean B = true;  while (true)   {   synchronized (r)    {    if (r.flag)      try    {     r.wait ();   }   catch ( Exception e)    {      }   if (b)    {    r.name= "Mike";     r.sex= "man";    b=false;   }   else   {    r.name= "Lili";     r.sex= "female female female";    b=true;   }   r.flag=true;   r.notify ();   } } }} class Output implements Runnable{ res R; output (Res r)  {  this.r=r;& nbsp;}  public void Run ()  {  while (true)   {   synchronized (R)    {    if (! R.flag)      try     {      r.wait ();     }    Catch (Exception e)     {        }        system.out.println ( R.name+ "..." +r.sex);   r.flag=false;  r.notify ();   } } }}   Continue for example: multiple threads are responsible for production, and multiple threads are responsible for consumption. Note Notifyall and while (flag)   for multiple producers and consumers. Why would you define a while judgment tag? Let the awakened thread judge the token again.   Why define Notifyall because you need to wake the other thread. Because only with notify, it is easy to wake up the thread only, causing all threads in the program to wait.    public class Test{ public static void Main (String args [])  {  Resource r = new Resource () ;  Producer Pro = new Producer (r);  Consumer con = new Consumer (r);   Thread t1 = new Thread (PRO); &nbs P Thread t2 = new Thread (con);  thread t3 = new Thread (PRO);  thread t4 = new thread (con);  t1.start ();  T2.start ();  T3.start ();  t4.start ();   }} class resource{ private String name;  private int count = 1; private Boolean flag = false;  public synchronized void set (String name)  {&nbsp ; while (flag)    try  {    Wait (); }  catch (Exception e)   {    }& nbsp THIS.name = name+ "--" +count++;  SysTem.out.println (Thread.CurrentThread (). GetName () + "... Producer: " +this.name);   flag = true;  this.notifyall ();  } public synchronized void out ()  {  while (!flag)    try  {    Wait (); }  catch (Exception e)   {    }& nbsp System.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+this.name);  flag = false;  this.notifyall ();  } } class Producer implements Runnable{ private Resource res; public void Run ()  {  while (true)   {   res.set ("+ Commodity + "); } } producer (Resource res)  {  This.res=res; }} class Consumer implements Runnable{ private Resource res; public void Run ()  {  while (true)   {   res.out ();  } } consumer (Resource res)  {  this.res=res; } }   Jdk5 after upgrade   Java.util.concurrent.locks InterfaceThe  jdk1.5 provides a multi-threaded upgrade solution that replaces the synchronized synchronized with the lock operation, replacing the Wait,notify,nofityall in object with the condition object, which can be lock-locked, To obtain. A lock can correspond to multiple condition. A multi-threaded upgrade solution is available in  jdk1.5. Replace the synchronous synchronized with the real lock operation. Replaces the condition object with the Wait,notify Notifyall in object. The object can be obtained by lock lock. In this example, the party only wakes the other action.  lock: Instead of Synchronized lock unlock new Condition ()  condition: Replaces object wait notify Notifyall await ();  signal ();  signalall ();   in this power, realizes that the party only wakes each other's operation. Code after change:  import java.util.concurrent.locks.*; class test{ public static void Main (string[] args)  {  Resource r = new Resource ();   Producer Pro = new Producer (r);  Consumer con = new Consumer (r );   Thread T1 = new Thread (PRO);  thread t2 = new Thread (PRO);  thread t3 = new Thread (con);  Th Read T4 = new Thread (con);   t1.start ();  T2.start ();  T3.start ();  t4.start ();   }} A multi-threaded upgrade solution is available in  /*jdk1.5. Replace the synchronous synchronized with the real lock operation. The objectReplaces the condition object with the Wait,notify Notifyall in the. The object can be obtained by lock lock. In this example, the party only wakes the other action.  lock: Replaces Synchronized lock unlock newcondition ()  condition: Replaces object wait notify Notifyall await ();  signal ();  signalall (); */class resource{ private String name; private int count = 1; private Boolean flag = false;   // t1    t2 private Lock lock = new Ree Ntrantlock ();  private Condition Condition_pro = lock.newcondition ();  private Condition Condition_con = Lock.newcondition ();     public  void set (String name) throws interruptedexception {   Lock.lock ();  try  {   while (flag)     condition_pro.await ();//t1,t2    THIS.name = name+ "--" +count++;    system.out.println (Thread.CurrentThread (). GetName () + "... Producer: " +this.name);   flag = true;   condition_con.signal (); }  finally  {    Lock.unlock ();//InterpretationThe lock action must be performed.  } }   // t3   T4   public  void out () throws interruptedexception& nbsp {  lock.lock ();  try  {   while (!flag)     condition_con.await ();    System.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+this.name);   flag = false;   condition_pro.signal (); }  finally  {    lock.unlock (); }  }} class Producer implements Runnable{ private Resource Res;   producer (Resource res)  {  this.res = Res; } public void Run ()  {  while (true )   {   try   {    Res.set ("+ goods +");   }   catch ( Interruptedexception e)    {   }    } }} class Consumer implements Runnable{ private Resource Res;  consumer (Resource res)  {  this.res = res; }  public void Run () &nbSp {  while (true)   {   try   {    res.out ();   }   catch ( Interruptedexception e)    {   } } }}     stopping a thread  The only way to stop threading is to end the thread with the run () method. Interrupt//Forced wakeup The Stop method is obsolete. How do I stop a thread? Only one, the Run method ends. Turn on multi-threaded running, and running code is usually a looping structure.  As long as you control the loop, you can let the Run method end, that is, the thread ends. Special case: When the thread is in a frozen state. The tag is not read. Then the thread will not end. When there is no specified way to get the frozen thread back to the running state, then the freeze needs to be cleared. Forces the thread to revert to the running state. This makes it possible to manipulate the tag to end the thread.    The thread class provides the method interrupt (); Set as the daemon thread, when all other threads are finished, and only the daemon thread is left, the daemon thread ends automatically and must be set earlier before start (). Join MethodT1.join (); Rob CPU execution, when the T1 execution ends, the main line friend thawed. Join: When a thread executes the. Join () method of the B thread, a waits. When the b thread is executed, a will not execute. Join can be used to temporarily join thread execution. priority of the thread         self-written code: import Java.util.concurrent.locks.*;import java.util.concurrent.locks.lock.*;  public class Test{ public static void Main (String args[])  {  Resource r = new Resource ();  Pro p = new Pro (r);  cro C = new Cro (r);  thread T1 = new Thread (p);  thread t2 = new Thread (p);  thread T3 = new Thread (c);  thread T4 = new Thread (c);  T1.start ();  T2.start ();  T3.start ();  T4.start ();    }} class resource{  private Boolean flag = false; private int count = 1; & Nbsp;private Lock lock = new Reentrantlock ();  private Condition Con_pro = lock.newcondition ();  private Condition Con_con = lock.newcondition ()   public void set ()  {    lock.lock ();       Try {     while (flag)      con_pro.await ();     count++ ;     system.out.println (Thread.CurrentThread ().GetName () + "produced the first +count+" ticket ");     flag=true;     con_con.signal ();   } catch (Interruptedexception e) {        }    finally    {     lock.unlock ();   }& nbsp      }   public void Hua ()  {    lock.lock ();        Try {     while (!flag)      con_con.await ();      System.out.println (Thread.CurrentThread (). GetName () + "Consumption of the first" +count+ "Ticket * * *");     flag=false;     con_pro.signal ();   } catch (Interruptedexception e) {        }  &N Bsp finally    {     lock.unlock ();   }    }  } class Pro implements Runnable{ resource R; pro (Resource r)  {  this.r=r; }  public void Run ()  {  while (true)   &NBsp;r.set ();  }} class Cro implements Runnable{ resource R; cro (Resource r)  {  this.r=r ;  }  public void Run ()  {  while (true)    r.hua ();  }}

JAVA 11 (multithreaded)

Related Article

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.