编程语言
首页 > 编程语言> > java实现多线程的四种方式

java实现多线程的四种方式

作者:互联网

实现多线程的三种方式:继承Thread类、实现Runnable接口、使用Callable和Future接口、使用线程池创建线程

一、继承Thread类,重写run方法

public class MyThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("我在听音乐");
        }
    }

    public static void main(String[] args) {

        MyThread myThread = new MyThread();
        myThread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程");
        }
    }
}

二、实现Runnable接口

public class MyThread2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("我在听音乐");
        }
    }

    public static void main(String[] args) {

        Thread myThread = new Thread(new MyThread2());
        myThread.start();

        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程");
        }
    }
}

三、使用Callable和Future接口创建线程

public class MyThread4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Test test = new Test();
        FutureTask<Integer> ft = new FutureTask<>(test);
        Thread thread = new Thread(ft);

        thread.start();
        for (int i = 0; i < 200; i++) {
            System.out.println("我在学习多线程");
        }

        //获取返回值
        ft.get();

    }

    static class Test implements Callable<Integer>{

        @Override
        public Integer call() throws Exception {
            for (int i = 0; i < 200; i++) {
                System.out.println("我在听音乐");
            }

            return null;
        }
    }
}

四、使用线程池创建线程
实现Callable接口,需要返回值类型
重写call方法,需要抛出异常
创建目标对象
创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(3);
提交执行:Future sub1 = ser.submit(test1);
获取结果:Integer integer1 = sub1.get();
关闭服务:ser.shutdownNow();

public class MyThread3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Test test1 = new Test(1);
        Test test2 = new Test(2);
        Test test3 = new Test(3);
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Integer> sub1 = ser.submit(test1);
        Future<Integer> sub2 = ser.submit(test2);
        Future<Integer> sub3 = ser.submit(test3);
        //获取结果
        Integer integer1 = sub1.get();
        Integer integer2 = sub2.get();
        Integer integer3 = sub3.get();
        //关闭服务
        ser.shutdownNow();

    }

    static class Test implements Callable<Integer>{

        private int a;

        public Test(int a) {
            this.a = a;
        }

        @Override
        public Integer call() throws Exception {
            for (int i = 0; i < 20; i++) {
                System.out.println("我在听音乐"+a);
            }

            return null;
        }
    }
}

标签:java,ser,Thread,int,Test,new,多线程,public,四种
来源: https://www.cnblogs.com/tanhongwei/p/16602009.html