There are three ways to implement Java multithreading.
1, inherits the thread class (actually implements the Runable interface).
2. Implement the Runable interface.
3. Use Executorservice, callable, and future to implement multithreading with return results. The first two do not return the results, if you want to find a return to the results of a lot of trouble will be flawed.
Example:
1. Inherit the thread class.
public class Test extends thread{
Need to rewrite run
public void Run () {
System.out.println ("Thread go");
}
public static void Main (string[] args) {
The build thread requires a new test () and the properties inside the test are not shared between threads.
Test T1 = new test ();
Test t2 = new Test ();
T1.start ();
T2.start ();
If you call the Run method directly, T1.run (), execute the main function process, you can refer to the thread JDK source code.
}
}
2. Implement the Runable interface
public class Test implements runable{
private int count=5;
Need to rewrite run
public void Run () {
for (; count>0;count--;)
System.out.println ("Thread go" +count);
}
public static void Main (string[] args) {
The build thread requires a new test () and is shared among the property threads inside test.
Test T1 = new test ();
You need to build the thread using the methods provided by the thread class
Tread Th1 = new Thread (t1, "Thread 1");
Tread Th2 = new Thread (t2, "Thread 2");
Th1.start ();
Th2.start ();
}
}
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:
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 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 the result of the run, the current task time" "+" + "milliseconds";
}
}
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.
Section Code reference: http://blog.csdn.net/aboy123/article/details/38307539
Java Multithreading Summary