Three ways to create threads

Source: Internet
Author: User

first, inherit the thread class + rewrite the Run () method

Start: Create Subclass Object + object. Start ()
Disadvantage: Java only supports single inheritance, and if our class has been inherited from a class , it is no longer possible to inherit the thread class.

 PackageThread;/** * Mock Turtle Rabbit Race * 1, create multithreading (mode one): Inherit thread + override run method (thread body) * 2, use thread: Create subclass Object + object. Start () method thread start */Public class Demo01 {public static void Main (string[] args) {//Create sub-class objectRabbit rab =NewRabbit (); Tortoise Tor =NewTortoise ();//Call the Start method to start the thread. Internal CPU ControlRab.start ();//Do not call the Run method, called by the internal itself. Tor.start (); for(int i=0;i< -; i++) {System.out.println ("Main-->"+i); }    }} class Rabbit extends Thread{    //thread body Everything starts with run    @Overridepublic void Run () {//Thread body         for(int i=0;i< -; i++) {System.out.println ("Rabbit ran."+i+"Step"); }    }} class tortoise extends Thread {@Overridepublic void Run () {//Thread body         for(int i=0;i< -; i++) {System.out.println ("The Turtle ran away."+i+"Step"); }    }}
Second, implement the Runnable interface + rewrite the Run method

start: use static proxy
1), create a real role
2), create a proxy role
3), call the Start () method to start the thread
Pros: You can implement inheritance at the same time, runnable interface way more general.
1, avoid the limitations of single inheritance
2. Easy to share resources
Multithreading is achieved by implementing the Runnable interface. ( static proxy design mode is used)
http://blog.csdn.net/scgaliguodong123_/article/details/44025531

 PackageThread;/** * Recommended use of runnable to create threads * 1, to avoid the limitations of single inheritance * 2, easy to share resources * * Public  class Demo03 {     Public Static void Main(string[] args) {//1), create a real roleProgrammer Pro =NewProgrammer ();//2), create proxy role + real role referenceThread proxy =NewThread (PRO);//3), call the Start () method to start the threadProxy.start (); for(intI=0;i< -; i++) {System.out.println ("Chatting QQ"); }    }}/** * Create a process using runnable * 1, class implementation runable interface + rewrite run () method * 2, start multithreading using static proxy * 1), create a real role * 2), create a proxy role * 3), call Start ( ) method to start the thread * /Class Programmer implements runnable{@Override     Public void Run() { for(intI=0;i< -; i++) {System.out.println ("hit the code."); }    }}
 PackageThread;/** * Rob Ticket system * Easy to share resources * * Public  class Demo04 implements Runnable{    Private intnum = -;@Override     Public void Run() { while(true){if(num<=0)            { Break;//Jump out of the loop} System.out.println (Thread.CurrentThread (). GetName () +"Got to the bottom."+num--+"Zhang. "); }    } Public Static void Main(string[] args) {//Real roleDemo04 Web =NewDemo04 ();//AgentThread T1 =NewThread (web,"Demacia"); Thread t2 =NewThread (web,"Katrina"); Thread t3 =NewThread (web,"Chancellor of the state of Lourdes");//Start threadT1.start ();        T2.start ();    T3.start (); }}
third, use the callable interface to create multithreading

Callable and future interfaces
Callable are similar to runnable interfaces, classes that implement *callable interfaces and classes that implement Runnable are tasks that can be performed by other threads *.
Pros: You can return a value and throw an exception.
Cons: tedious to implement.

steps:
1. Implement callable interface + Rewrite call method

2. Get the object with the execution dispatch service ExecutorService Future

ser = Executors.newFixedThreadPool(2);ser.submit(tortoise);

3. Get the value result
int num = result.get();The Get method return value is a generic

4. Stop the Serviceser.shutdownNow();

 PackageThread;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.Future;/** * Create multithreading using the Callable interface * / Public  class Demo05 {     Public Static void Main(string[] args)throwsInterruptedexception, Executionexception {///1, creating ThreadsExecutorservice ser = Executors.newfixedthreadpool (2);//Open Two threadsRace Tortoise =NewRace ("Old Turtle", +); Race rabbit =NewRace ("Little bunny.", -);///2, Get future objectsfuture<integer> result1 = ser.submit (tortoise);        future<integer> result2 = Ser.submit (rabbit); Thread.Sleep ( -);//2 secTortoise.setflag (false);//Stop thread body loop set flag = FALSE;Rabbit.setflag (false);///3, Get value        intNUM1 = Result1.get ();intnum2 = Result2.get (); System.out.println ("The turtle ran."+num1+"Step"); System.out.println ("The rabbit ran."+num2+"Step");//4, stop serviceSer.shutdownnow (); }}class Race implements callable<integer>{PrivateString name;//Name    Private LongTime//Delay Time    Private BooleanFlag =true;Private intStep =0;//Step     Public Race() {    } Public Race(String name) {Super(); This. name = name; } Public Race(String name,intTime) {Super(); This. name = name; This. Time = time; }//has a return value    @Override     PublicIntegerPager()throwsException { while(flag) {Thread.Sleep (time);//Delaystep++; }returnStep } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public Long GetTime() {returnTime } Public void settime(LongTime) { This. Time = time; } Public Boolean Isflag() {returnFlag } Public void Setflag(BooleanFlag) { This. flag = Flag; } Public int Getstep() {returnStep } Public void SetStep(intStep) { This. Step = Step; }}

Operation Result:

乌龟跑了-->3步兔子跑了-->5步
four, callable and runnable a few different:

(1) The method prescribed by callable is call (), and the method specified by runnable is run ().

(2) Callable can return a value after a task is executed, and Runnable's task cannot return a value.

(3) The call () method throws an exception , and the Run () method cannot throw an exception.

(4) Run the callable task to get a future object , the futurerepresents the result of an asynchronous calculation . It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation. The future object allows you to understand task execution, cancel the execution of a task, and get the results of a task execution.

Three ways to create threads

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.