Java Concurrency (e) an overview of ways to create threads

The following outlined several ways to create a thread, not expanded in-depth, you can understand.

First, implement Runnable


1. Business class implements Runnable interface
2.Thread injection traffic class type and start
code is as follows:

public class RunnableDemo {
    public static void main(String[] args) {
        //Thread构造器注入实现类并启动
        new Thread(new RunnableWorker()).start();
    }
}

//实现Runnable接口
class RunnableWorker implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }
    }
}
复制代码

Second, the Thread class inheritance


Business class inheritance Thread, the thread can be run directly in the way. code show as below:

public class ThreadDemo extends Thread {

    public static void main(String[] args) {
        new ThreadDemo().start();
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }
    }
}
复制代码

Third, to achieve Callable Interface


Traffic class may implement Callable interface or Runnable interface Callable difference between the two is performed after the return value, the return value is not Runnable.
code show as below:

public class FutureDemo {
    public static void main(String[] args) {
        FutureTask<Integer> task = new FutureTask(new CallableWorker());

        new Thread(task).start();

        try {
            System.out.println(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class CallableWorker implements Callable<Integer> {

    public Integer call() throws Exception {
        return 10;
    }
}
复制代码

Four, Executors building


Traffic class may implement Callable interface or Runnable interface Callable difference between the two is performed after the return value, the return value is not Runnable.
code show as below:

public class ExecutorsDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        //提交匿名Callable
        Future<Integer> future = executorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return 10;
            }
        });

        //获取线程执行返回值
        System.out.println(future.get());
    }
}
复制代码

end.


Site: javashizhan.com/


Micro-channel public number:


Guess you like

Origin juejin.im/post/5d94d958e51d45780b56832d