Three ways to implement multithreading in Java

Source: Internet
Author: User

There are two ways to implement multithreading in Java: Inheriting the thread class and implementing the Runnable interface

1. Inherit the thread class, overriding the parent class run () method

  public class thread1 extends Thread {          public void run ()  {                 for  (int i = 0; i < 10000;  i++)  {                         system.out.println ("I Am Thread" +this.getid ());                 }         }         public static void  main (String[] args)  {                 thread1 th1 = new thread1 ();            &nBsp;    thread1 th2 = new thread1 ();                 th1.run ();                 th2.run ();         }     }

run () method is only a normal method and is executed sequentially, that is, Th1.run () executes Th2.run () after execution, so that only one main thread is written. Multithreading is meaningless, so you should start the thread with the start () method, and the start () method automatically calls the run () method. The above code should read:

 public class thread1 extends Thread {                 public void run ()  {                 for  (int i =  0; i < 10000; i++)  {                         system.out.println (" I am Thread "+this.getid ());                 }        }          Public static void main (String[] args)  {                 thread1 th1 = new thread1 ();      &nBsp;          thread1 th2 = new thread1 ( );                 th1.start ();                 th2.start ();         }}

Start a new thread with the start () method. This way, regardless of whether the run () method of the Th1.start () call is complete, continue execution Th2.start () if the following code does not need to wait for Th2.start () to finish, and continue. (The thread ID of the output is an irregular alternating output)


2. Implement the Runnable interface

public class thread2 implements runnable {          public String ThreadName;                 public thread2 (String tname) {                 ThreadName = tName;         }                         public void run ()  {                 for  (int  i = 0; i < 10000; i++)  {                          System.out.println (threadname);                 }         }                 public static void main (String[] args)  {                 thread2 th1 = new  Thread2 ("Thread A");                 thread2 th2 = new thread2 ("Thread B");                 th1.run ();                 th2.run ();         }}

As with the thread's Run method, the runnable run is just a normal method, and in the Main method Th2.run () must wait for Th1.run () to execute before it executes, and the program uses only one thread. For multi-threading purposes, also through the start () method of the thread (note :runnable there is no Start method ). The code above is modified to:

public class thread2 implements runnable {          public String ThreadName;                 public thread2 (String tname) {                 ThreadName = tName;         }                         public void run ()  {                 for  (int  i = 0; i < 10000; i++)  {                          System.out.println (threadname);                 }         }                 public static void main (String[] args)  {                 thread2 th1 = new  Thread2 ("Thread A");                 thread2 th2 = new thread2 ("Thread-b");                 thread myth1 = new thread (Th1);                 Thread  Myth2 = new thread (Th2);                 myth1. Start ();                 Myth2.start ();         }}

3. Use Executorservice, callable, and future to implement multi-threaded (JDK5.0 later)

import java.util.concurrent.*;  import java.util.date;  import  java.util.list;  import java.util.arraylist;    /** *  a thread that has a return value  */   @SuppressWarnings ("unchecked")   public class Test {   Public static void main (String[] args)  throws ExecutionException,   &NBSP;&NBSP;&NBSP;&NBSP;INTERRUPTEDEXCEPTION&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("---- The program starts running----");      date 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> (&NBSP;&N);bsp;   for  (int i = 0; i < tasksize; i++)  {       callable c = new mycallable (i +  " ");       //  perform tasks and get future objects       future f  = pool.submit (c);       // system.out.println (">>>"  + f.get (). toString ());       list.add (f);      }     //  Close thread pool      pool.shutdown ();        //  get run results for all concurrent tasks      for  (future f  :  list)  {      //  get the return value of the task from the future object and output it to the console        system.out.println (">>>"  + f.get (). toString ());      }    &nbsP;  date date2 = new date ();      system.out.println ("-- --Program End run----, program run Time ""        +  (Date2.gettime ()  -  Date1.gettime ())  +  "MS");   }  }    class mycallable  implements Callable<Object> {  private String taskNum;     mycallable (String tasknum)  {     this.taskNum =  Tasknum;  }    public object call ()  throws exception {      system.out.println (">>>"  + taskNum +  "task start");      date datetmp1 = new date ();      Thread.Sleep (+);      date datetmp2 = new date ();      long time =&nbsP;datetmp2.gettime ()  - datetmp1.gettime ()      system.out.println (">> > " + taskNum + " task termination ");     return tasknum + " The task returns the result of the run, the current task time ""  + time +  "millisecond";   }  }

Code Description:
The executors class in the code above provides a series of factory methods for creating a first thread pool, and the returned thread pool implements the Executorservice interface.
Public static Executorservice newfixedthreadpool (int nthreads)
creates a thread pool of a fixed number of threads.
Public static Executorservice Newcachedthreadpool ()
creates a cacheable thread pool that calls execute to reuse previously constructed threads if the threads are available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds.
Public static Executorservice Newsinglethreadexecutor ()
Create a single-threaded executor.
Public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)
Create a thread pool that supports timed and recurring task executions, which in most cases can be used to replace the timer class.
Executoreservice provides the Submit () method, passing a callable, or runnable, back to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete.

Summary: 2 ways to implement Java Multi-threading, Runable is an interface, thread is a class, runnable only provides a run method, it is recommended to use Runable to implement Java multi-threading, regardless, eventually need to pass Thread.Start () To keep the thread in a running state. The third method is to listen to the brothers in the group introduced, so Baidu fill up.


Three ways to implement multithreading in Java

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.