java create thread mode

1. Inherit Thread class

public class ThreadCreator extends Thread{

    public static void main(String[] args) {
//The first way: ThreadCreator creator
= new ThreadCreator(); Thread thread = new Thread(creator,"Thread 1");
thread.start();
//The second way:
Thread thread = new ThreadCreator();
thread.start();
//The third way:
new ThreadCreator().start();
   } @Override
public void run() { System.out.println(Thread.currentThread().getName() + "run"); } }

 

2. Implement the Runnable interface

public class ThreadCreator implements Runnable{

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

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

3. Implement 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");
       thread.start();
       System.out.println(futureTask.get());
    }

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

4. Thread pool ExecutorService

public class ThreadCreator{

   static ExecutorService service = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //execute No return value
        service.execute(new ThreadTask(1,"1"));
        //submit Return value
        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; } } }

The difference between submit and execute in the thread pool:

① the types of acceptable tasks are different: execute can only accept Runnable tasks, and submit can also accept Callable tasks.

② 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 return value of type Future to receive the return value or respond to the exception. Get it through the get() method.

The bottom layer of submit is still called execute, but on this basis, it encapsulates one layer with future, and encapsulates all the exceptions generated in the execution process in one 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();
        }
    }

In addition, the schedule annotation in spring uses submit for reference.

5. Anonymous inner class

public class ThreadCreator {

    public static void main(String[] args) {

        //inherit Thread class
        new Thread() {
            @Override
            public void run() {
                System.out.println("extends Thread Class!");
            }
        }.start();
        //Realization Runnable Interface
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("implement Runnable!");
            }
        }).start();
        //Realization Callable Interface
        new Thread(new FutureTask<Integer>(new Callable() {
            @Override
            public Integer call() throws Exception {
                return 1024;
            }
        })).start();
        //lambda Expression
        new Thread(() -> System.out.println("execute single code")).start();
        new Thread(() -> {
            System.out.println("execute multiple code");
        }).start();
    }
}

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()); //No return value
        Future future = service.submit(() -> execute()); //Return value
        list.add(future);
    }

    public static void execute() {
        //do something
    }
}

Tags: Java Lambda Spring

Posted on Sun, 05 Jan 2020 13:47:48 -0800 by d22552000