上一篇:并发编程(1)—— 基础概念

创建线程的方式

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口,配合FutureTask

一、继承Thread类

public class NewThred  {

    public static void main(String[] args) {
        Thread testThread = new TestThread();
        testThread.setName("The testThread's name thread");
        testThread.start();
    }

    public static class TestThread extends Thread{
        @Override
        public void run(){
            System.out.printf(Thread.currentThread().getName());
        }
    }
}

运行结果:

 The testThread's name thread

二、实现Runnable接口

public class NewThred  {

    public static void main(String[] args) {
        Thread testRunnable = new Thread(new TestRunnable());
        testRunnable.setName("The testRunnable's name runnable");
        testRunnable.start();
    }

    public static class TestRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
}

运行结果:

The testRunnable's name runnable

三、实现Callable,配合使用FutureTask

public class NewThred  {

    public static void main(String[] args) {
        Callable<String> testCallable = new TestCallable();
        FutureTask<String> futureTask = new FutureTask<>(testCallable);
        Thread thred = new Thread(futureTask);
        thred.setName("The testCallable's name callable");
        thred.start();
        
        try {
            System.out.printf("返回值:"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static class TestCallable implements Callable<String>{
        @Override
        public String call() throws Exception {
            System.out.println(Thread.currentThread().getName());
            return Thread.currentThread().getName();
        }
    }
}

运行结果:

The testCallable's name callable
返回值:The testCallable's name callable

下一篇:并发编程(3)——interrupt()中断线程