实现线程的三种方式

实现线程的三种方式

  • 继承Thread类
  • 实现Runnable接口
  • 实现Callable接口
package thread;

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

/**
 * 线程测试
 * @author sunlh
 *
 */
public class ThreadTest {

    public static void main(String[] args) {

        // 通过实现Runnable接口实现多线程
        ThreadTest.implRunnable();
        // 通过继承Thread类实现多线程
        ThreadTest.extThread();
        // 通过实现Callable接口来实现多线程
        ThreadTest.callableThread();
    }

    /**
     * 通过实现Runnable接口来实现线程
     */
    public static void implRunnable() {
        Thread thread = new Thread(new RunnableImpl(), "实现Runnable的线程");
        thread.start();
    }

    /**
     * 通过继承Thread类来实现线程
     */
    public static void extThread() {
        MyThread thread = new MyThread();
        thread.setName("继承Thread的线程");
        thread.start();
    }

    /**
     * 通过实现Future来实现有返回值的线程
     */
    public static void callableThread() {
        FutureTask task = new FutureTask<>(new CallableImpl());
        Thread thread = new Thread(task);
        thread.setName("具有返回值的Callable线程");
        thread.start();
        try {
            String result;
            result = task.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class CallableImpl implements Callable {

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return "我是Callable线程的返回值";
    }

}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

class RunnableImpl implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 实现线程的三种方式
本站总访问量: , 本页阅读量: