Multithreading in Java

Source: Internet
Author: User
Tags date1 instance method

I would like to summarize the multithreading in Java, has been resistant to no time. The third kind of work is really often used.

There are three main ways to implement Java Multithreading:

1, inherit the thread class,

2, realize runnable interface,

3, the use of Executorservice, callable, the future to achieve a return result of multi-threading.

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. Directly on the test code.

Public class MyThread extends Thread {

Public void Run () {

System.out.println ("Mythread.run ()");

}

public static void Main (string[] args) {

MyThread myThread1 = new MyThread ();

MyThread myThread2 = new MyThread ();

Mythread1.start ();

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.

Public class MyThread extends Otherclass implements Runnable {

Public void Run () {

System.out.println ("Mythread.run ()");

}

public static void Main (string[] args) {

MyThread MyThread = new MyThread ();

Thread thread = new Thread (myThread);

Thread.Start ();

}

}

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

Public void Run () {

if (target! = null) {

Target.run ();

}

}


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.

a task that needs to return a value must implement the callable interface , and similarly, a task that has no return value must implement the Runnable 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. The code that goes directly to the return value.

Package Javademo;
Import java.util.concurrent.*;
Import Java.util.Date;
Import java.util.List;
Import java.util.ArrayList;

/**
* Thread with return value
*/
@SuppressWarnings ("Unchecked")
public class Executorservicetest {
public static void Main (string[] args) throws Executionexception,
interruptedexception {
SYSTEM.OUT.PRINTLN ("----program starts running----");
Date date1 = new Date ();

int tasksize = 5;
Create a pool of threads
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 tasks and get future objects
Future F = Pool.submit (c);
System.out.println (">>>" + f.get (). toString ());
List.add (f);
}
Close the thread pool
Pool.shutdown ();

Get run results for all concurrent tasks
for (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 ()) + "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 + "task termination");
return tasknum + "task returns run result, current task time" "+" "+" "milliseconds";
}
}

There's more to say here.
The executors class in the code above provides a series of factory methods for creating a 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.

At this time the music sounded again, "there you on the way" ... You know, love you is not easy, but also need a lot of courage ....

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.