Several ways of process creation

Four common ways to create threads in Java

1. Rewrite the run method of the Thread class

1.1, the new Thread object anonymously overrides the run method

 new Thread(){
    
    
            @Override
            public void run() {
    
    
                System.out.println("进程创建方式1.1");
            }
        }.start();

1.2, inherit Thread, rewrite run method

class MyThread extends Thread{
    
    
            @Override
            public void run() {
    
    
                System.out.println("进程创建方式1.2");
            }
        }
        new MyThread().start();

2. Implement the Runable interface and rewrite the run method

2.1, new Runable object, anonymously rewrite run method

   Runnable runnable = new Runnable(){
    
    
            @Override
            public void run() {
    
    
                System.out.println("进程创建方式2.1");
            }
        };
        new Thread(runnable).start();

2.2. Implement the Runable interface and rewrite the run method

class MyRuncable implements Runnable{
    
    

            @Override
            public void run() {
    
    
                System.out.println("进程创建方式2.2");
            }
        }
        new Thread(new MyRuncable()).start();

3. Implement the Callable interface and use the FutureTask class to create threads

 class MyCallable implements Callable{
    
    
            @Override
            public String call() throws Exception {
    
    
                System.out.println("调用 call");
                return "进程创建方式3";
            }
        }
        FutureTask ft = new FutureTask(new MyCallable());
        new Thread(ft).start();
        try {
    
    
            System.out.println("输出结果:"+ft.get());
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        } catch (ExecutionException e) {
    
    
            e.printStackTrace();
        }

4. Use the thread pool to create and start threads

 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.submit(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("进程创建方式4");
            }
        });
        singleThreadExecutor.shutdown();

Guess you like

Origin blog.csdn.net/qianzhitu/article/details/108233879