Home > Java > Javagetting Started > body text

Summary of how to create threads in java

王林
Release: 2020-01-08 16:59:06
forward
2156 people have browsed it

Summary of how to create threads in java

1. Inherit the Thread class

public class ThreadCreator extends Thread{

    public static void main(String[] args) {
       //第一种方式:
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
       //第二种方式:
       Thread thread = new ThreadCreator();
       thread.start();
       //第三种方式:
       new ThreadCreator().start();
   }
 
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}
Copy after login

2. Implement the Runnable interface

(free learning video tutorial sharing: java video tutorial)

public class ThreadCreator implements Runnable{

    public static void main(String[] args) {
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}
Copy after login

3. Implement the Callable interface

public class ThreadCreator implements Callable<Integer> {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
       ThreadCreator creator = new ThreadCreator();
       FutureTask futureTask = new FutureTask(creator);
       Thread thread = new Thread(futureTask,"线程");
       thread.start();
       System.out.println(futureTask.get());
    }

    @Override
    public Integer call() {
        return 1024;
    }
}
Copy after login

4. Thread pool ExecutorService

public class ThreadCreator{

   static ExecutorService service = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //execute无返回值
        service.execute(new ThreadTask(1,"1"));
        //submit有返回值
        Future<Integer> result = service.submit(new ThreadTaskCall());
        System.out.println(result.get());
        service.shutdownNow();
    }
    static class ThreadTask implements Runnable{
        private int param1;
        private String param2;
        public ThreadTask(int param3,String param4){
            this.param1 = param3;
            this.param2 = param4;
        }
        @Override
        public void run() {
            System.out.println(param1+param2);
        }
    }

    static class ThreadTaskCall implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            return 1024;
        }
    }
}
Copy after login

The difference between submit and execute in the thread pool:

(1 ) The acceptable task types are different: execute can only accept Runnable tasks, and submit can also accept Callable tasks.

(2) Return value: execute has no return value. Once the task is submitted, the execution result cannot be monitored in the current thread. Submit has a Future type return value, which is used to receive return values ​​or respond to exceptions. Obtained through the get() method.

The bottom layer of submit is still called execute, but it is encapsulated with a future layer on this basis, and all exceptions generated during the execution are encapsulated in a variable:

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }
Copy after login

In addition, spring The schedule annotation uses the submit processing method for reference.

5. Anonymous inner class

public class ThreadCreator {

    public static void main(String[] args) {

        //继承Thread类
        new Thread() {
            @Override
            public void run() {
                System.out.println("extends Thread Class!");
            }
        }.start();
        //实现Runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("implement Runnable!");
            }
        }).start();
        //实现Callable接口
        new Thread(new FutureTask<Integer>(new Callable() {
            @Override
            public Integer call() throws Exception {
                return 1024;
            }
        })).start();
        //lambda表达式
        new Thread(() -> System.out.println("execute single code")).start();
        new Thread(() -> {
            System.out.println("execute multiple code");
        }).start();
    }
}
Copy after login

lambda thread pool:

public class ThreadCreator {

    static ExecutorService service = Executors.newFixedThreadPool(5);

    static List list = new ArrayList();

    public static void main(String[] args) {
        service.execute(() -> execute()); //无返回值
        Future future = service.submit(() -> execute()); //有返回值
        list.add(future);
    }

    public static void execute() {
        //do something
    }
}
Copy after login

Recommended related article tutorials: java quick start

The above is the detailed content of Summary of how to create threads in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template