There are three kinds:
(1) Inheriting the thread class, overriding the Run function
Create:
Class XX extends thread{public
void Run () {
thread.sleep (1000) /thread sleeps 1000 milliseconds, sleep causes the thread to enter the block state, and frees the resource
}}
To open a thread:
Object. Start ()//boot thread, run function
(2) Implement runnable interface and rewrite the run function
To open a thread:
Thread t = new Thread (object) //Create Threads Object
T.start ()
(3) Implement callable interface, rewrite call function
Callable are interfaces similar to runnable, 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:
①callable The method specified is call (), and runnable the method is run ().
A ②callable task can return a value after execution, whereas a runnable task cannot return a value
The ③call () method throws an exception, and the run () method cannot throw an exception.
④ run callable task to get a future object, future represents the result of an asynchronous computation. It provides a way to check whether the calculation is complete and so on
The completion of the calculation, and retrieve the results of the calculation. The future object allows you to understand the execution of the task, cancel the execution of the task, and get the results of the task execution
Java Callable code Example:
Class Taskwithresult implements callable<string> {
private int id;
public taskwithresult (int id) {
this.id = ID;
}
@Override public
String called () throws Exception {return ' result of
Taskwithresult ' + id;
}
}
public class Callabletest {public
static void Main (string[] args) throws Interruptedexception,
executionexception {
Executorservice exec = Executors.newcachedthreadpool ();
arraylist<future<string>> results = new arraylist<future<string>> (); Future is equivalent to a container for executor execution results
(int i = 0; i < i++) {
results.add exec.submit (New Taskwithresul T (i)));
for (future<string> fs:results) {
if (Fs.isdone ()) {
System.out.println (Fs.get ());
} else {
System.out.println ("Future result are not yet complete");
}
Exec.shutdown ();
}
Run Result:
result of Taskwithresult 0
Result of taskwithresult 1
result to Taskwithresult 2
Result of Taskwithresult 3
result by Taskwithresult 4
Result of Taskwithresult 5
Result of Taskwithresult 6
Resul T of Taskwithresult 7
Result-Taskwithresult 8
Result of Taskwithresult 9