Three ways to interpret Java multithreading in detail _java

Source: Internet
Author: User

Recently in the code optimization to learn and study the use of Java multithreading, read the rookie's opinion after doing a summary.

1, inheritance thread class to achieve multithreading

Methods that inherit the thread class although I am listed as a multithreaded implementation, thread is essentially an instance of the Runnable interface, which represents an instance of a thread, and the only way to start a thread is through the thread class's start () instance method. The start () method is a native method that starts a new thread and executes the run () method. This approach to multithreading is simple, by using your own class to extend thread directly, and by copying the run () method, you can start a new thread and execute your own defined run () method. For example:

public class Mythread extends Thread {public 
void run () { 
System.out.println ("Mythread.run ()"); 
} 
} 

Start the thread in the appropriate place as follows:

Mythread myThread1 = new Mythread (); 
Mythread myThread2 = new Mythread (); 
Mythread1.start (); 

2, implement Runnable interface mode to achieve multithreading

If your class is already extends another class, you cannot extends Thread directly, at which point you must implement a runnable interface, as follows:

public class Mythread extends Otherclass implements Runnable {public 
void run () { 
System.out.println ("Mythre  Ad.run () "); 
} 
} 

In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:

Mythread mythread = new Mythread (); 
Thread thread = new Thread (mythread); 

In fact, when a runnable target parameter is passed to thread, the thread's Run () method invokes Target.run (), referencing the JDK source code:

public void Run () { 
if (target!= null) { 
target.run (); 
} 

3, using Executorservice, callable, future to achieve a return of the results of multithreading

Executorservice, callable, future This object is actually a functional class within the executor framework. Here is a very detailed explanation of the framework. The thread that returns the result is a new feature introduced in the JDK1.5, which is really practical, and with this feature I don't have to bother to get a return value, and even if it does, it can be a lot of holes.

A task that can return a value must implement the callable interface, and similarly, a task with no return value must runnable the interface. After performing the callable task, you can get a future object that invokes get on the object to obtain the object returned by the callable task, and then combine the thread pool interface Executorservice to achieve the legendary return of the results of multithreading. The following provides a complete example of a multithreaded test with return results, which can be used directly under JDK1.5. The code is as follows:

Import java.util.concurrent.*; 
Import Java.util.Date; 
Import java.util.List; 
 
Import java.util.ArrayList; /** * Thread with return value/@SuppressWarnings ("Unchecked") public class Test {public static void main (string[] args) throws Exe 
  Cutionexception, interruptedexception {System.out.println ("----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> (); 
  for (int i = 0; i < tasksize i++) {callable c = new Mycallable (i + ""); 
  Perform the task and get the Future object Future f = pool.submit (c); 
  System.out.println (">>>" + f.get (). toString ()); 
  List.add (f); 
 
  ///Close thread pool Pool.shutdown (); Gets the run result for all concurrent tasks for (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 finishes running----, program run time"" + (Date2.gettime ()-date1.gettime ()) + "millisecond"); 
 
} 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 (1000); 
  Date DATETMP2 = new Date (); 
  Long time = Datetmp2.gettime ()-datetmp1.gettime (); 
  System.out.println (">>>" + Tasknum + "mission terminated"); 
return tasknum + "The task returns the running result, the current task time" "+ Times +" milliseconds ""; 
 } 
}

Code Description:

The executors class in the above code provides a series of factory methods for the first thread pool, and the returned thread pool implements the Executorservice interface.

public static Executorservice newfixedthreadpool (int nthreads)

Creates a thread pool of fixed number of threads.

public static Executorservice Newcachedthreadpool ()

Creates a cacheable thread pool, and calling execute reuses the previously constructed thread (if the thread is available). If an existing thread is not available, create a new thread and add it to the pool. Terminates and removes threads from the cache 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 periodic task execution, which in most cases can be used instead of the timer class.

Executoreservice provides a submit () method that passes a callable, or runnable, back to future. If the executor background thread pool has not completed the callable calculation, this call returns the Get () method of the future object, blocking until the calculation is complete.

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.