Java Multi-Threading

Source: Internet
Author: User
Tags thread stop

Tag:package   object   public    Consumer    double    

package com.yuanzijian01;/* *   thread Communication:  when a thread finishes its task, it notifies another thread to complete another task .  Producer and Consumer Wait ():   waiting     If the thread executes the wait method, the thread goes into a wait state, and the thread in the wait state must be called by another thread to wake up the Notify method. Notify ():  wake up      wake thread pool waiting for one of the threads. Notifyall ()  :  wake thread pool all wait   threads. Wait and Notify methods to note: The 1. wait method and the Notify method belong to the object  . The 2. wait method and the Notify method must be used in a synchronous code block or in a synchronous function to  . The 3. wait method and the Notify method must be called by the lock object. Problem one: There is a thread safety issue.   Price disorder ...  *///product class class product{string name;double price;boolean flag =  false;} Class producer extends thread{product p;    publicproducer (Product  p) {    this.p = p;    } @Overridepublic  void  Run ()  {// TODO  auto-generated method stub super.run (); Int i = 0;while (True) {synchronized (p) {if ( P.flag==false) { if (i%2==0) { p.name =  "Apple";  p.price = 6.5;&nbSP;} Else{ p.name= "Banana";  p.price = 2.0; } system.out.println ("producer produces:" + p.name+ "   Price is: "+ p.price";  p.flag = true; i++; p.notifyall ();  //awaken consumers to consume      }else{    try{    p.wait ();     } catch (interruptedexception e) {    e.printstacktrace ();    }     }}}}}//Consumer class customer extends thread{product p; public   customer (Product p)  {this.p = p;} @Overridepublic  void run ()  {while (True) {synchronized  (p)  {if (p.flag==true) {   //products have been produced System.out.println ("Consumer Consumption of" +p.name+ "  Price:" + p.price);p .flag = false;  P.notifyall (); //  wake-up producers to produce}else{//products have not yet been produced, should   wait for producers to produce first. Try {p.wait ();  //consumers are waiting ...}  catch  (interruptedexception e)  {e.printstacktrace();}}}}}} Public class demo01 {public static void main (String[] args)  {//  todo  automatically generated method stub product p = new product ();   //product//Create production Object producer  Producer = new producer (P);//Create Consumer Customer customer = new customer (p);// Call the Start method to turn on thread Producer.start (); Customer.start ();}}

2. Thread Stop

package com.yuanzijian01;/* *   thread Communication:  when a thread finishes its task, it notifies another thread to complete another task .  Producer and Consumer Wait ():   waiting     If the thread executes the wait method, the thread goes into a wait state, and the thread in the wait state must be called by another thread to wake up the Notify method. Notify ():  wake up      wake thread pool waiting for one of the threads. Notifyall ()  :  wake thread pool all wait   threads. Wait and Notify methods to note: The 1. wait method and the Notify method belong to the object  . The 2. wait method and the Notify method must be used in a synchronous code block or in a synchronous function to  . The 3. wait method and the Notify method must be called by the lock object. Problem one: There is a thread safety issue.   Price disorder ...  *///product class class product{string name;double price;boolean flag =  false;} Class producer extends thread{product p;    publicproducer (Product  p) {    this.p = p;    } @Overridepublic  void  Run ()  {// TODO  auto-generated method stub super.run (); Int i = 0;while (True) {synchronized (p) {if ( P.flag==false) { if (i%2==0) { p.name =  "Apple";  p.price = 6.5;&nbSP;} Else{ p.name= "Banana";  p.price = 2.0; } system.out.println ("producer produces:" + p.name+ "   Price is: "+ p.price";  p.flag = true; i++; p.notifyall ();  //awaken consumers to consume      }else{    try{    p.wait ();     } catch (interruptedexception e) {    e.printstacktrace ();    }     }}}}}//Consumer class customer extends thread{product p; public   customer (Product p)  {this.p = p;} @Overridepublic  void run ()  {while (True) {synchronized  (p)  {if (p.flag==true) {   //products have been produced System.out.println ("Consumer Consumption of" +p.name+ "  Price:" + p.price);p .flag = false;  P.notifyall (); //  wake-up producers to produce}else{//products have not yet been produced, should   wait for producers to produce first. Try {p.wait ();  //consumers are waiting ...}  catch  (interruptedexception e)  {e.printstacktrace();}}}}}} Public class demo01 {public static void main (String[] args)  {//  todo  automatically generated method stub product p = new product ();   //product//Create production Object producer  Producer = new producer (P);//Create Consumer Customer customer = new customer (p);// Call the Start method to turn on thread Producer.start (); Customer.start ();}}

3. Daemon thread

package com.yuanzijian03;/* daemon Thread (background thread): The daemon thread will die if only   daemon threads are left in a process. Demand:  simulation QQ download update package. A thread by default is not a daemon thread. */public class demo03 extends thread {public demo03 (String name) {Super (name );} @Overridepublic  void run ()  {for (int i = 1 ; i<=100 ; i++) {System.out.println ("update package currently downloads" +i+ "%"), if (i==100) {System.out.println ("update package download complete, ready to install ...");} Try {thread.sleep (100);}  catch  (interruptedexception e)  {e.printstacktrace ();}} Public static void main (String[] args)  { Demo03 d = new  Demo03 ("Background thread");  d.setdaemon (true);  //setdaemon ()   Sets whether the thread is a daemon thread, true is a daemon thread, and  false is a non-daemon thread.  system.out.println ("Is it a daemon thread?") "+ d.isdaemon ()");  //determines whether the thread is a daemon thread.  d.start ();   for (int i = 1 ; i<=100 ; i++) {  System.out.println (Thread.CurrentThread (). GetName () + ":" +i);  } }}

4.join method Join

Package cn.itcast.thread;/* join method.   Join   *///mom Class  mon extends thread{public void run ()  { System.out.println ("Mother washes vegetables"); System.out.println ("Mother cut Vegetables"); System.out.println ("Mother ready to stir-fry, found no soy sauce anymore."); /Call his son to soy sauce Son s= new son (); S.start (); Try {s.join ();   //join.   A thread if a join statement is executed, then a new thread joins, and the thread executing the statement must give in to the newly joined line enters upgradeable to complete the task before it can continue execution. } catch  (interruptedexception e)  {e.printstacktrace ();} System.out.println ("mother continues to stir fry"); System.out.println ("Dinner with the whole Family");}}  class son extends thread{@Overridepublic  void run ()  {system.out.println (" Son downstairs. "); Try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} System.out.println ("The son has been walking forward"); System.out.println ("The son finishes the soy sauce"); System.out.println ("Go upstairs, give the soy sauce to Mom");} Public class demo8 {public static void main (String[] args)  {Mon m  = new mon (); M.start ();}} 


Java Multi-Threading

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.