Mock cooking system (join method in java+ thread)

Source: Internet
Author: User

(I) Project Framework Analysis

Mom is going to cook, find no soy sauce, let her son buy soy sauce, and then come back to Cook.

According to Object-oriented thinking, there are two objects, mother and son

There are two main methods:

(a) There is no Line program control (that is, the son did not buy soy sauce back mother cooked Dinner) + (no call Jion METHOD)

(b) Wired Program Control (mother process and son process and successively Influence) + (call jion METHOD)

Structure diagram of the project:

(ii) No Process Control Mintak

Son.java mainly simulates the Son's actions, the son buys the soy sauce action (same as the source program with process Control)

The code is as Follows:

 public classSonImplementsRunnable { public voidrun () {System.out.println ("son went out to buy soy sauce."); System.out.println ("it takes five minutes to get back to my son."); //buying soy sauce process        Try{             for(inti=1;i<=5;i++) {thread.sleep (1000); System.out.print (i+ "minutes"); }        }Catch(interruptedexception ie) {System.out.println ("\ nthe son bought soy sauce back."); }    }}

Mother.java mainly simulates mother's behavior,

The main code is as follows

 packagecom.cjg.normal;Importcom.cjg.mistak.Son; public classMotherImplementsRunnable { public voidRun () {//output The corresponding information, that mother found no soy sauce, called son to buy soy sauce backSystem.out.println ("mother prepares to cook rice"); System.out.println ("mom found out the soy sauce was exhausted."); System.out.println ("mom told her son to buy soy sauce."); Thread son=NewThread (NewSon ());        Son.start (); System.out.println ("mother waits for son to buy soy sauce back"); Try{            //after two threads have been successfully merged, the execution of the MOM thread must wait until the son thread finishes executingSon.join (); }Catch(interruptedexception Ie) {//output the appropriate informationSystem.err.println ("an Exception occurred! "); System.err.println ("mother interrupted cooking!" "); System.exit (1); }        //son buys soy sauce home, mother starts cookingSystem.out.println ("mother begins to cook rice"); System.out.println ("mom's cooking."); }}

Cooking.java is to test whether mom and Son's class implements the cooking

Import com.cjg.mistak.Mother;  public class Cooking {    publicstaticvoid  main (String argv[]) {        New Thread (new  mother ());}    }
(iii) process-controlled

Mainly the content in the Mother.java class is different,

Specific code for the Mother.java class:

 packagecom.cjg.normal;Importcom.cjg.mistak.Son; public classMotherImplementsRunnable { public voidRun () {//output The corresponding information, that mother found no soy sauce, called son to buy soy sauce backSystem.out.println ("mother prepares to cook rice"); System.out.println ("mom found out the soy sauce was exhausted."); System.out.println ("mom told her son to buy soy sauce."); Thread son=NewThread (NewSon ());        Son.start (); System.out.println ("mother waits for son to buy soy sauce back"); Try{            //after two threads have been successfully merged, the execution of the MOM thread must wait until the son thread finishes executingSon.join (); }Catch(interruptedexception Ie) {//output the appropriate informationSystem.err.println ("an Exception occurred! "); System.err.println ("mother interrupted cooking!" "); System.exit (1); }        //son buys soy sauce home, mother starts cookingSystem.out.println ("mother begins to cook rice"); System.out.println ("mom's cooking."); }}
(iv) status of the thread (4-1) basic state

Threads also have a life cycle, with 5 states in their life cycle, new (created), runnable (waiting to run), running (run), blocked (paused), and dead (end).

The relationship between them

When the thread class object is generated, the object is in the new state, and the start () method is called to enter the runnable State. If the CPU calls the thread, it enters the running state from the runnable state, running the code in the Run () method of the thread, as Follows:

(4-2) the suspended state of the thread

corresponding to the thread object, if you want to implement it to temporarily stop, but after the recovery runs without generating a new thread object, you need to learn how to put the thread in a paused State. There are 4 ways we can achieve this:

1.sleep () method

Sleep This word in English means sleeping, mainly for the realization of the thread object to sleep, but in the sleep set the alarm clock, the time will be back to run, the method is Used:

thread.sleep (long Millis)

Millis represents the time of sleep, the unit of time is 1 per thousand seconds, if you want to sleep 1s, you need to pass in 1000

  When a thread class object wakes up, it does not enter the running state immediately, but enters the runnable state First.

2.yield () method

When the CPU is calling a thread to run, it needs to call the sleep () method if the thread is asleep for a period of time, and if the thread does not want to run at this point, it can call the yield () method.

For the sleep () method, the thread must not transition from the running state to the runnable state at the specified time;

For the yield () method, the thread may immediately transition from the running state to the runnable State.

The basic methods to use Are:

Thread.yield ()

3.join () method

The join () method is required when thread 1 needs to wait for thread 2 to complete an event before it can continue to execute when the threads in the runnable state are several threads.

The basic format used is as Follows:

Thread.Join ()

4.wait () Method and Nofity () method

The wait () method is very similar to the join () method, and for the join () method, thread 1 waits for thread 2 to complete something before it can continue, and thread 2 completion indicates that the thread has died naturally, whereas for the wait () method, only thread 2 calls Nofity () method to wake up thread 1 before it can Execute.

(4-3) End state of thread

There are two ways to end a thread: natural extinction and forced extinction.

Natural extinction: refers to a thread that returns from the end of its run () method, and dies naturally after execution ends.

Forced extinction: refers to forcing a thread to end with the stop () method in the thread class, which is not recommended.

Mock cooking system (join method in java+ thread)

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.