Thread:
CPU scheduling and distribution of basic unit, the basic need of system resources, has only a little in the operation of essential resources
Four ways to create a thread
1. implement Runnable, override run method
specific methods:
class RunnableDemo implements Runnable{
public void run() {
for (int i = 0, j=10;i<j;i++){
System.out.println(i);
}
}
}
transfer:
RunnableDemo runnableDemo = new RunnableDemo();
new Thread(runnableDemo).start();
2. Thread class inheritance, override the run method
specific methods:
class ThreadDemo extends Thread{
@Override
public void run() {
for (int i = 0, j=10;i<j;i++){
System.out.println(i);
}
}
}
transfer:
new ThreadDemo().start();
3. To achieve callable interface rewrite method call
class CallableDemo implements Callable<Integer>{
public Integer call() {
int sum = 0;
for (int i = 0, j=10;i<j;i++){
System.out.println(i);
sum+=i ;
}
return sum;
}
}
transfer:
CallableDemo callableDemo = new CallableDemo();
FutureTask<Integer> futureTask = new FutureTask<Integer>(callableDemo);
new Thread(futureTask).start();
System.out.println(futureTask.get());
Description :
a FutureTask, inherited from RunnableFuture, RunnableFuture inherited from Runnable so you can create a thread (polymorphism)
use futureTask.get (), you will get the return value,But the thread is not enabled