Java多线程——之一创建线程的四种方法

JAVA学习网 2018-10-16 12:40:02

 

1.实现Runnable接口,重载run(),无返回值

public class ThreadRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread() + ":" + i);
        }
    }
}

public class ThreadMain {
    public static void main(String[] args)
    {
        ThreadRunnable threadRunnable = new ThreadRunnable();
        未完待续
    }
}

  

2.继承Thread类,复写run()

使用时通过调用Thread的start()(该方法是native),再调用创建线程的run(),不同线程的run方法里面的代码交替执行。

不足:由于java为单继承,若使用线程类已经有个父类,则不能使用该方式创建线程。

public class ThreadEx extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread() + ":" + i);
        }
    }
}


public class ThreadMain {
    public static void main(String[] args)
    {
        ThreadEx threadEx = new ThreadEx();
        threadEx.start();
    }
}

  

3.实现Callable接口,通过FutureTask/Future来创建有返回值的Thread线程

补充:与实现Runnable接口类似,都是实现接口,不同的是该方式有返回值,可以获得异步执行的结果。

延伸:FutureTask是类,Future是接口。

import java.util.concurrent.Callable;

public class ThreadCallable implements Callable {
    public Object call() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread() + ":" + i);
        }
        return "succeed";
    }
}

  

4.使用Executors创建ExecutorService,入参Callable或Future

补充:适用于线程池和并发

 

 

未完待续,补充源码

阅读(2484) 评论(0)