Three ways to implement Java multithreading

Source: Internet
Author: User
Tags date1 instance method

Java Multi-threaded implementation of the main three kinds: inherit the thread class, implement Runnable interface, use Executorservice, callable, the future implementation has the result of multithreading. There are no return values for the first two methods after the thread has finished executing, only the last one with the return value.

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

[Java]View PlainCopy
    1. Public class MyThread extends Thread {
    2.   Public void Run () {
    3. System.out.println ("Mythread.run ()");
    4. }
    5. }

Start the thread in the appropriate place as follows:

[Java]View PlainCopy
    1. MyThread myThread1 = new MyThread ();
    2. MyThread myThread2 = new MyThread ();
    3. Mythread1.start ();
    4. Mythread2.start ();


2, realize the Runnable interface way to realize multithreading
If your class already extends another class, you cannot directly extends the Thread, at which point you must implement a runnable interface, as follows:

[Java]View PlainCopy
    1. Public class MyThread extends Otherclass implements Runnable {
    2.   Public void Run () {
    3. System.out.println ("Mythread.run ()");
    4. }
    5. }

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

[Java]View PlainCopy
    1. MyThread MyThread = new MyThread ();
    2. Thread thread = new Thread (myThread);
    3. Thread.Start ();

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

[Java]View PlainCopy
    1. Public void Run () {
    2.   if (target! = null) {
    3. Target.run ();
    4. }
    5. }


3, the use of Executorservice, callable, the future to achieve a return result of multi-threading
Executorservice, callable, future This object is actually a function class in the executor framework. To learn more about the accessible http://www.javaeye.com/topic/366591 of the executor framework, here is a detailed explanation of the framework. The thread that returns the result is a new feature introduced in JDK1.5, and it's really practical, and with this feature I don't have to go any further to get the return value, and it can be flawed even if it's done.
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:

[Java]View PlainCopy
  1. Import java.util.concurrent.*;
  2. Import Java.util.Date;
  3. Import java.util.List;
  4. Import java.util.ArrayList;
  5. /**
  6. * Thread with return value
  7. */
  8. @SuppressWarnings ("unchecked")
  9. Public class Test {
  10. Public static void Main (string[] args) throws Executionexception,
  11. interruptedexception {
  12. System.out.println ("----program starts running----");
  13. Date date1 = new Date ();
  14. int tasksize = 5;
  15. //Create a thread pool
  16. Executorservice pool = Executors.newfixedthreadpool (tasksize);
  17. //Create multiple tasks with return values
  18. list<future> list = new arraylist<future> ();
  19. For (int i = 0; i < tasksize; i++) {
  20. Callable C = new mycallable (i + "");
  21. //Perform tasks and get future objects
  22. Future F = Pool.submit (c);
  23. //System.out.println (">>>" + f.get (). toString ());
  24. List.add (f);
  25. }
  26. //close thread pool
  27. Pool.shutdown ();
  28. //Get running results for all concurrent tasks
  29. For (f:list) {
  30. //Get the return value of the task from the future object and output it to the console
  31. System.out.println (">>>" + f.get (). toString ());
  32. }
  33. Date Date2 = new Date ();
  34. System.out.println ("----program ends running----, program run Time" "
  35. + (Date2.gettime ()-date1.gettime ()) + "millisecond" ");
  36. }
  37. }
  38. Class Mycallable implements Callable<object> {
  39. Private String Tasknum;
  40. Mycallable (String tasknum) {
  41. this.tasknum = Tasknum;
  42. }
  43. Public Object call () throws Exception {
  44. System.out.println (">>>" + tasknum + "task start");
  45. Date DATETMP1 = new Date ();
  46. Thread.Sleep (1000);
  47. Date DATETMP2 = new Date ();
  48. Long time = Datetmp2.gettime ()-datetmp1.gettime ();
  49. System.out.println (">>>" + tasknum + "task termination");
  50. return Tasknum + "task returns run result, current task time" "+" "+ " "milliseconds";
  51. }
  52. }

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.

Reproduced in: http://www.cnblogs.com/yezhenhan/archive/2012/01/09/2317636.html

from:http://blog.csdn.net/aboy123/article/details/38307539

Three 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.