Today review threading knowledge, found a very interesting small program, is used to explain the multi-threaded under the post-sharing, for beginners to understand the thread has a great help
The story of father and son
<span style= "font-family:kaiti_gb2312;font-size:18px;" >public class Fatherthread extends thread{@Override public void Run () {System.out.println ("Dad wants to smoke And found that the smoke was exhausted "); System.out.println ("Father let son to buy bag Hongtashan"); Thread son = new Sonthread (); Son.start (); System.out.println ("Daddy waits for his son to buy cigarettes back"); try {//join meaning: Wait for the son thread to finish executing, Father line friend continue to execute Son.join (); } catch (Interruptedexception e) {System.out.println ("where Dad went out to find his son"); System.exit (1); } System.out.println ("Dad happily took the cigarette and gave the change to his son"); }} </span>
<span style= "font-family:kaiti_gb2312;font-size:18px;" >public class Sonthread extends thread{@Override public void Run () {String tags = "\t\t\t\t\t"; System.out.println (tags+ "son went to buy cigarettes"); System.out.println (tags+ "Son to buy cigarettes for 10 minutes"); try {for (int i =0; i<10;) {thread.sleep (1000); System.out.println (tags+ "son out of the first" + ++i + "Minutes"); }} catch (Interruptedexception e) {e.printstacktrace (); } System.out.println (tags+ "son went to buy cigarettes back"); }} </span>
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class Main {public static void Main (string[] args) { System.out.println ("Story of Papa and Son"); Thread fathread =new fatherthread (); Fathread.start (); try { thread.sleep; } catch (Interruptedexception e) { //TODO auto-generated catch block E.printstacktrace (); }}} </span>
Run Results
The story of father and son
Dad wanted to smoke and found the smoke was over.
Dad asked his son to buy a bag Hongtashan
Dad waits for his son to buy cigarettes.
Son went to buy cigarettes.
It takes 10 minutes for my son to buy cigarettes.
Son out for the 1th minute
Son out for the 2nd minute
Son out for the 3rd minute
Son out for the 4th minute
Son out for the 5th minute
Son out for the 6th minute
Son out for the 7th minute
Son out for the 8th minute
Son out for the 9th minute
Son out for the 10th minute
Son went to buy cigarettes and came back.
Dad was happy to take the cigarette and gave the change to his son.
The program enters the main function, first father the thread begins execution. Father asked his son to buy cigarettes, and then wait for his son to buy cigarettes back, then son thread start 10 minutes after the boy back Fathrer thread continue to execute.
Copyright NOTICE: This article for Bo Master original article, reproduced please indicate the source, thank you!
Father and son's story takes you to understand Java threads