并发编程之创建线程的四种方式

继承Thread类

步骤

  • 定义一个Thread类的子类,重写run方法,将相关逻辑实现,run()方法就是线程要执行的业务逻辑方法
  • 创建自定义的线程子类对象
  • 调用子类实例的star()方法来启动线程

代码

public class MyThread  {
    
    


    public static void main(String[] args) {
    
    

        MyThreadInner myThreadInner = new MyThreadInner();
        myThreadInner.start();
    }


    static class MyThreadInner extends Thread{
    
    
        @Override
        public void run() {
    
    
            System.out.println(Thread.currentThread().getName() + " run()方法正在执行...");
        }
    }
}

实现Runable接口

步骤

  • 定义Runnable接口实现类MyRunnable,并重写run()方法
  • 创建MyRunnable实例myRunnable,以myRunnable作为target创建Thead对象,该Thread对象才是真正的线程对象
  • 调用线程对象的start()方法

代码

public class MyRunnable {
    
    

    public static void main(String[] args) {
    
    

        MyRunnableInner myRunnableInner = new MyRunnableInner();

        Thread thread = new Thread(myRunnableInner);
        thread.start();
    }

    private static class MyRunnableInner implements Runnable{
    
    
        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
    
    
            System.out.println(Thread.currentThread().getName() + " run()方法执行中...");
        }
    }

使用Callable和Future创建线程

步骤

  • 创建实现Callable接口的类myCallable
  • 以myCallable为参数创建FutureTask对象
  • 将FutureTask作为参数创建Thread对象
  • 调用线程对象的start()方法

代码

public class MyCallable {
    
    

    public static void main(String[] args) {
    
    

        FutureTask<Integer> future = new FutureTask<Integer>(new MyCallableInner());
        Thread thread = new Thread(future);
        thread.start();

        try {
    
    
            Thread.sleep(1000);
            System.out.println("返回结果 " + future.get());
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        } catch (ExecutionException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " main()方法执行完成");

    }


    private static class MyCallableInner implements Callable<Integer> {
    
    
        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public Integer call() throws Exception {
    
    
            System.out.println(Thread.currentThread().getName() + " call()方法执行中...");
            return 1;
        }
    }
}

使用Executor框架创建线程池

Executors提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。

主要有newFixedThreadPool,newCachedThreadPool,newSingleThreadExecutor,newScheduledThreadPool,后续详细介绍这四种线程池:

代码

public class SingleThreadExecutor {
    
    

    public static void main(String[] args) {
    
    

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for(int i=0;i<10;i++){
    
    

            MyRunnableInner myRunnableInner = new MyRunnableInner();
            executorService.execute(myRunnableInner);
        }
        System.out.println("线程任务开始执行");
        executorService.shutdown();

    }


    private static class MyRunnableInner implements Runnable{
    
    

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
    
    
            System.out.println(Thread.currentThread().getName() + " run()方法执行中...");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jinian2016/article/details/108683040