线程的三种创建方式

1. 继承Thread类
(1)定义Thread类的子类,并重写run()方法。
(2)创建Thread子类的实例,即创建线程对象。
(3)通过调用线程对象的start()方法启动该线程。

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread子类MyThread的线程号:" + currentThread().getName());
    }
}

public class Demo {
    public static void main(String[] args) throws Exception {
        test();
    }

    public static void test() throws Exception {
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}

2. 实现Runnable接口(常用)
(1)定义Runnable接口的实现类。
(2)创建Runnable的实现类实例,将此实例作为Thread的target来创建Thread对象。
(3)通过调用线程对象的start()方法启动该线程。

class MyThreadImpl implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable接口的线程号:" + Thread.currentThread().getName());
    }
}
public class Demo {
    public static void main(String[] args) throws Exception {
         test();
    }

    public static void test() throws Exception {
       MyThreadImpl mti = new MyThreadImpl();
        Thread t1 = new Thread(mti);
        t1.start();
    }
}

3.实现Callable接口
(1)定义Callable接口的实现类,并实现call()方法,call()方法有返回值。
(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
(3)将FutureTask对象作为Thread对象的target创建线程对象,调用start()启动新线程。
(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。

class MyThreadCallable implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("实现Callable接口的线程号:" + Thread.currentThread().getName());
        return 10;
    }
}
public class Demo {
    public static void main(String[] args) throws Exception {
         test();
    }
    public static void test() throws Exception {
        Callable callable = new MyThreadCallable();
        FutureTask ft = new FutureTask(callable);
        Thread t = new Thread(ft);
        t.start();
        System.out.println(ft.get());   
   }
}
posted @ 2020-11-03 19:10  mydiray  阅读(180)  评论(1)    收藏  举报