Four ways to create threads (a)

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

Lack of study time, too shallow knowledge, that's wrong, please forgive me.

There are 10 kinds of people in the world, one is to understand binary, one is do not understand binary.

Published 71 original articles · won praise 54 · views 420 000 +

Guess you like

Origin blog.csdn.net/weixin_43326401/article/details/104095849