重学Java之创建线程

Java 中创建线程有3 种方式:

  • 继承 Thread 类
  • 实现 Runnable 接口
  • 使用 Callable 和 FutureTask :FutureTask 本质上是 Runnable 接口,只是实现方式和 Runnable 不一样,所以单独放出来

继承Thread

编写一个 MyThread 类,继承 Thread ,重写 run() 方法,run() 方法就是具体要执行的任务。

调用 start() 方法来执行线程。

public class CreateThread {

    public static void main(String[] args) throws InterruptedException {
    	System.out.println("main() , " + Thread.currentThread().getName());
        MyThread thread = new MyThread();
        thread.start();
}

class MyThread extends Thread{

    @Override
    public void run() {
        super.run();
        System.out.println("MyThread [" + Thread.currentThread().getName() +"] running... ");
    }
}

运行结果,

main() , main
MyThread [Thread-0] running...

要看当前是哪个线程,调用 Thread.currentThread() 即可。

如果想自定义线程名字,可以加上构造函数 Thread(String name) ,

class MyThread extends Thread{

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        super.run();
        System.out.println("MyThread [" + Thread.currentThread().getName() +"] running... ");
    }
}

新建线程时传入线程名称,

MyThread thread = new MyThread("A");
thread.start();

实现 Runnable 接口

编写一个类实现 Runnable 接口 ,重写 run() 方法。

把 Runnable 接口实例传给 Thread ,调用 Thread.start() 方法执行。

public class CreateThread {

    public static void main(String[] args) throws InterruptedException {
        Thread  thread2 = new Thread(new MyRunnable());
        thread2.run();
}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("MyRunnable running...");
    }
}

使用 Callable 和 FutureTask

编写一个 MyCallable 类,实现 Callable 接口,重写 call() 方法,

创建 FutureTask 实例,把 MyCallable 类实例传给 FutureTask ,

把 FutureTask 实例作为参数传给 Thread 创建线程,

FutureTask 对象的 get() 方法来获得线程执行结束后的返回值。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CreateThread {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main() , " + Thread.currentThread().getName());
        MyCallable callable = new MyCallable();
        FutureTask futureTask = new FutureTask<>(callable);

        new Thread(futureTask).start();
        System.out.println("futureTask.get():" + futureTask.get());
}

class MyCallable implements Callable{

    @Override
    public Integer call() throws Exception {
        System.out.println("MyCallable [" + Thread.currentThread().getName() + "] call ...");
        int k = 0;
        for (; k < 5; k++){

        }
        return k;
    }
}

运行结果,

main() , main
MyCallable [Thread-1] call ...
futureTask.get():5

FutureTask 本质上是 Runnable ,

// FutureTask
public class FutureTask implements RunnableFuture {

	public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
}


//RunnableFuture
public interface RunnableFuture extends Runnable, Future {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

你可能感兴趣的:(Java,多线程,thread)