[JAVA]JAVA实现多线程的三种方式

一、继承Thread类,经过start()方法调用java

public class MultiThreadByExtends extends Thread {
    @Override
    public void run() {
        print("听歌");
    }
    public static void print(String threadName){
        while (true) {
            System.out.println("线程:"+threadName+" 输出。。。");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        MultiThreadByExtends t1 = new MultiThreadByExtends();
        t1.start();
        print("写代码");
    }
}

 

输出结果:面试

 
 

线程:写代码 输出。。。
线程:听歌 输出。。。
线程:写代码 输出。。。
线程:听歌 输出。。。
线程:写代码 输出。。。
线程:听歌 输出。。。
线程:听歌 输出。。。ide

 

因为java单继承的特色,这种方式局限性很大,不能继承其余父类spa

 

二、实现Runable接口线程

public class MultiThreadByRunnable implements Runnable {
    @Override
    public void run() {
        print("听歌");
    }
    public static void print(String threadName){
        while (true) {
            System.out.println("线程:"+threadName+" 输出。。。");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        MultiThreadByRunnable tr1 = new MultiThreadByRunnable();
        //代理方式启动
        Thread thread = new Thread(tr1);
        thread.start();
        print("写代码");
    }
}

输出结果:代理

线程:写代码 输出。。。
线程:听歌 输出。。。
线程:写代码 输出。。。
线程:听歌 输出。。。
线程:听歌 输出。。。
线程:写代码 输出。。。
线程:听歌 输出。。。
线程:写代码 输出。。。

 

三、实现callable接口code

import java.util.concurrent.*;

public class CallableTest implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        int count = 0;
        while (true){
            System.out.println("1111");
            Thread.sleep(1000);
            count++;
            if(count >10) {
                break;
            }
        }
        return true;
    }

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

        CallableTest c = new CallableTest();
        ExecutorService es = Executors.newFixedThreadPool(1);
        Future<Boolean> res = es.submit(c);
        System.out.println(res.get());
        es.shutdownNow();
    }
}

该方式的优势是能够获得线程的返回值 blog

 

平时开发中经常使用到的就是一、2两种方式,至于第三种,属于JUC里面的东西,若是在面试中能答上来,对初级或中级java面试来讲绝对是加分项继承

相关文章
相关标签/搜索