Java_ 4 ways to implement multi-threading

Source: Internet
Author: User

In order to 34 months back to school spring recruit, have to review a thread of four ways to achieve, I hope Spring recruit can find a better company, refueling!

1. inheriting the Thread class

 classMyThreadextendsthread{Private intTicket = 5 ;  Public voidrun () { for(inti=0;i<100;i++){                         if( This. ticket>0) {System.out.println ("Sell ticket: Ticket =" + ticket--) ; }                 }         }};  Public classthreaddemo0{ Public Static voidMain (String args[]) {MyThread MT1=NewMyThread (); MyThread mt2=NewMyThread (); MyThread Mt3=NewMyThread ();       Mt1.run (); //Note: The call is run, not start
Mt2.run ();
Mt3.run (); } };

Class Mythread extends thread{                   private int ticket = 5;                             public void Run () {for                        (int i=0;i<100;i++) {                            if (this.ticket>0) {                                      System.out.println ("sell ticket: Ticket =" + ticket--);}}}     ;     public class threaddemo0{public             static void Main (String args[]) {                 Mythread mt1 = new Mythread ();                          Mythread mt2 = new Mythread ();                          Mythread mt3 = new Mythread ();                             Mt1.start ();                       Mt2.start ();                        Mt3.start ();              }    };

Note:Start () is used to start a thread, and when the start () method is called, the system opens a thread that is in the ready state (running state) through the start () method in the Thead class .
It is not running at this time, and once the CPU time slice is taken, the run () method is automatically started. You do not have to wait for the run () method to finish executing, or you can continue to execute the following code .
and The Run () method is thread in this line, just a function of the line thread, not multi-threading. If the call to run () is actually equivalent to calling a normal function, the direct call to the run () method must wait for the run () method to complete before executing the following code, so the execution path is only one, there is no thread characteristics, so when multithreaded execution to use the start () method instead of the run () method.
2. Implement Runnable Interface ( no return worthwhile task must implement Runnable interface, the task that can return value must implement callable interface )

 Public classRUNNABLE_XC { Public Static voidMain (string[] args) {M1 M1=NewM1 (); M2 m2=NewM2 (); Thread T1=NewThread (M1); Thread T2=NewThread (m2);        T1.start ();    T2.start (); }}classM1ImplementsRunnable { Public voidrun () {inti = 100;  while(I > 0) {System.out.println (i--); }    }}classM2ImplementsRunnable { Public voidrun () {inti = 100;  while(I > 0) {System.out.println (i--); }    }}

the above two methods after the completion of the task execution cannot get the result returned, if the above two methods, it is recommended to use Runnable, simply put, it's because single-Inheritance multiple implementations

3. implements the callable interface to create thread threads through the Futuretask wrapper ( no return worthwhile task must be implemented runnable< Span style= "font-family:" Microsoft Black "" lang= "ZH-CN" > interface, A task that can return a value must implement callable interface, important thing to say 2 times )

The callable interface (and only one method) is defined as follows: generic interface, the type that the call () function returns is the type of V passed in, and callable is often enabled with the Java thread pool:

Public interface callable<v>   {   V call () throws Exception;   

Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.FutureTask;

public class Mycallable implements callable<string> {

Public String Call () throws Exception {
int i = 100;
String rs = "false";
while (i > 0) {
System.out.println (i--);
if (i = = 50) {
Thread.Sleep (3000);
}
if (i = = 1) {
rs = "TRUE";
}
}
Return RS;
}

public static void Main (string[] args) {
callable<string> OneCallable0 = new mycallable (); Create a Futuretask<string> object from callable<string>:
callable<string> oneCallable1 = new mycallable ();
futuretask<string> oneTask0 = new futuretask<string> (ONECALLABLE0);
futuretask<string> OneTask1 = new futuretask<string> (ONECALLABLE1);

Thread oneThread0 = new Thread (ONETASK0); Create a thread object from futuretask<string>:
Thread oneThread1 = new Thread (ONETASK1);

Onethread0.start ();
Onethread1.start ();

try {
System.out.println (Onetask0.get ());
System.out.println (Onetask1.get ());//Results
} catch (Interruptedexception | Executionexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

}

4. use executorservice,callable, Future

Executorserviceis a thread pool interface, execute callable< Span style= "font-family:" Microsoft Black "" lang= "ZH-CN" > After the task, you can get a future Object that is called on the object get Callable Task returned object , combined executorservice interface enables multiple threads with returned results

 

Import Java.util.arraylist;import java.util.date;import Java.util.list;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.future;public class Th_pool {public static void main ( String[] args) throws Executionexception, interruptedexception {System.out.println ("----program starts running----");D ate date1 = new Date (); int tasksize = 5; Create a thread pool executorservice pool = Executors.newfixedthreadpool (tasksize); Create multiple tasks with return values list<future> list = new arraylist<future> (); for (int i = 0; i < tasksize; i++) {Callable c = New MyCallable3 (i + ""); Perform the task and get the Future object F = Pool.submit (c); List.add (f);} Close the thread pool Pool.shutdown ();//Gets the run result for all concurrent tasks for (the future f:list) {//Gets the return value of the task from the future object and outputs it to the console System.out.println ("> >> "+ f.get (). toString ());} Date Date2 = new Date (); SYSTEM.OUT.PRINTLN ("----program ends running----, program run Time" "+ (Date2.gettime ()-date1.gettime ()) +" milliseconds "");}} Class MyCallable3 implements callable<object> {private String tasknum; MyCallable3 (String tasknum) {this.tasknum = Tasknum;} Public Object Call () throws Exception {System.out.println (">>>" + tasknum + "task start");D ate dateTmp1 = new Date (); Thread.Sleep (;D ate dateTmp2 = new Date (), Long time = Datetmp2.gettime ()-datetmp1.gettime (); System.out.println (">>>" + tasknum + "task termination"), return Tasknum + "task return run result, current task time" "+" "+" "";}}

The thread will first review this, the hand has a little task, said and do not want to work overtime, so did not write so thin

Java_ 4 ways to implement 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.