3 ways to implement Java multithreading

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 classThread1extendsThread { Public voidrun () { for(inti = 0; I < 10000; i++) {System.out.println ("I am a thread" + This. GetId ()); }   }     Public Static voidMain (string[] args) {thread1 Th1=NewThread1 (); Thread1 Th2=NewThread1 ();       Th1.run ();   Th2.run (); }  }

The 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 classThread1extendsThread { Public voidrun () { for(inti = 0; I < 10000; i++) {System.out.println ("I am a thread" + This. GetId ()); }    }       Public Static voidMain (string[] args) {thread1 Th1=NewThread1 (); Thread1 Th2=NewThread1 ();        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 classThread2ImplementsRunnable { PublicString ThreadName;  Publicthread2 (String tname) {threadname=Tname; }                 Public voidrun () { for(inti = 0; I < 10000; i++) {System.out.println (threadname); }    }           Public Static voidMain (string[] args) {thread2 Th1=NewThread2 ("Thread A"); Thread2 Th2=NewThread2 ("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 the Th1.run () to execute before it executes, and the program uses only one thread. For multi-threading purposes, also go through the thread's Start () method (Note: Runnable is not a Start method). The code above is modified to:

 Public classThread2ImplementsRunnable { PublicString ThreadName;  Publicthread2 (String tname) {threadname=Tname; }                 Public voidrun () { for(inti = 0; I < 10000; i++) {System.out.println (threadname); }    }           Public Static voidMain (string[] args) {thread2 Th1=NewThread2 ("Thread A"); Thread2 Th2=NewThread2 ("Thread-b"); Thread myth1=NewThread (Th1); Thread myth2=NewThread (Th2);        Myth1.start ();    Myth2.start (); }}

3. Use Executorservice, callable, and future to implement multi-threading with returned results (JDK5.0 later)
A task that can return a value must implement the callable interface, and similarly, a task that has no return value must runnable the interface. After performing the callable task, you can get a future object, call get on the object to get to the callable task returned object, and combined with the thread pool interface Executorservice can realize the legend has the return result of multithreading. Here is a complete example of a multithreaded test with return results, which can be used directly under JDK1.5. The code is as follows:

Importjava.util.concurrent.*; Importjava.util.Date;Importjava.util.List;Importjava.util.ArrayList; /*** Thread with return value*/@SuppressWarnings ("Unchecked")  Public classTest { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {System.out.println ("----program starts running----"); Date Date1=NewDate (); intTasksize = 5; //Create a pool of threadsExecutorservice pool =Executors.newfixedthreadpool (tasksize); //Create multiple tasks with return valueslist<future> list =NewArraylist<future>();  for(inti = 0; i < tasksize; i++) {callable C=NewMycallable (i + "")); //perform tasks and get future objectsFuture F =Pool.submit (c); //System.out.println (">>>" + f.get (). toString ());List.add (f); }   //Close the thread poolPool.shutdown (); //get run results for all concurrent tasks   for(Future f:list) {//gets the return value of the task from the future object and outputs it to the consoleSystem.out.println (">>>" +f.get (). toString ()); } Date date2=NewDate (); System.out.println ("----program End run----, program run Time" "+ (Date2.gettime ()-date1.gettime ()) +" MS ""); } } classMycallableImplementsCallable<object> { PrivateString Tasknum; Mycallable (String tasknum) { This. Tasknum =Tasknum;}  PublicObject Call ()throwsException {System.out.println (">>>" + tasknum + "task Start"); Date DATETMP1=NewDate (); Thread.Sleep (1000); Date DATETMP2=NewDate (); LongTime = Datetmp2.gettime ()-Datetmp1.gettime (); System.out.println (">>>" + tasknum + "task termination"); returnTasknum + "task returns run result, current task 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.

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.

There are several differences between callable and runnable:,

The method prescribed by ①callable is call (), and the method specified by runnable is run ().
②callable can return a value after a task is executed, and Runnable's task cannot return a value.
The ③call () method throws an exception, and the run () method cannot throw an exception.
④ run the callable task to get a future object that represents the result of an asynchronous calculation. It provides a way to check whether a calculation is completed,

The calculation is completed and the results of the calculation are retrieved. The future object allows you to understand task execution, cancel task execution, and get the results of task execution

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.

3 ways to implement Java multithreading

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.