One is to inherit the thread class, one is to implement the Runable interface, and the other is to implement the callable interface;
There are bloggers said only the first 2 ways, I personally humble opinion is three kinds, the main details of the use of callable;
My personal understanding of three threads:
Thread is the simplest, simple and rough is the most basic, the replication run () method, start-up is good;
Runable is a modified version of the thread based on runable the main contribution is to achieve the sharing of resources, for example, the seat of the online seating resources need to share this time must use the runable, but he also needs the help of thread;
Callable is mainly used to deal with asynchronous, the thread itself is a time-consuming resource, so you sometimes need to wait for his processing results, this time need to callable;
How to use anonymous threadable;
new Thread ()
{
@Override
public Void Run ()
{
TODO auto-generated Method Stub
//do something here
}
}.start ();
How to create anonymous runable using
New Thread (new Runnable ()
{
@Override
public Void Run ()
{
TODO auto-generated Method Stub
Do something here
}
}). Start ();
How to create callable
Public class callabletest{
/**
The test case is remote asynchronous decryption;
*/
Public string Decryption (string _ciphertext) {
String result = "";
Create a pool of threads
Executorservice pool = executors.newfixedthreadpool (2);
Callable C = new Callabletest ();
Perform tasks and get future objects
Future f = pool.submit (c);//use with Data
//close thread pool
Pool.shutdown ();
try {
result = f.get (). toString ();
} catch (Interruptedexception e) {
result = "";
} catch (Executionexception e) {
result = "";
}
return result;
}
@SuppressWarnings("Rawtypes")
class Callabletest implements callable {
Different from the other two threads here the replication call () method
Public String Call () throws Exception {
DoSomething here;
}
}
}
Three ways to implement multithreaded programming in Java