【Java】线程创建的四种方式

1 前言

线程创建线程的方法一般可以分为四类:

  1. 通过实现Runnable接口来创建Thread线程
  2. 通过实现Callable接口来创建Thread线程
  3. 通过继承Thread类来创建一个线程
  4. 使用Executor框架来创建线程

2 创建线程的四种方式

2.1 实现Runnable接口创建Thread

通过实现Runnable接口来创建Thread线程,其步骤可以分为以下几步

  • 步骤1:创建一个类实现Runnable接口
class TestRunnable implements Runnable{
    public void run(){
    }
}
  • 步骤2:创建一个类对象
Runnable testRunnable = new TestRunnable();
  • 步骤3:由Runnable创建一个Thead对象
Thread testThread = new Thread(testRunnable);

步骤4:启动线程:

testThread.start();

至此,通过实现Runnable接口来创建线程的步骤完成。

代码实现如下所示:
(1)TestRunnable类

package com.yds.test;
public class TestRunnable implements Runnable {
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            i++;
        }
    }
}

(2)Test类调用

package com.yds.test;

public class Test {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //使用实现Runnable接口创建线程
        Runnable testRunnable = new TestRunnable();
        Thread testThread = new Thread(testRunnable);
        testThread.start();
    }

}

2.2 实现Callable接口来创建Thread线程

Callable是一个接口,只有一个call方法,用Callable接口创建Thread线程的步骤如下:

  • 步骤1:创建实现Callable接口的类TestCallable
package com.yds.test;

import java.util.concurrent.Callable;

public class TestCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            Thread.sleep(1000);
            i++;
        }
        return i;
    }

}

  • 步骤2:创建一个类对象
TestCallable testCallable = new TestCallable();
  • 步骤3:有Callable创建一个FutureTask对象
FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
  • 步骤4:由FutureTask对象创建一个Thread对象
Thread thread = new Thread(task);
  • 步骤5:启动线程
thread.start();

FutureTask的get方法是返回Callable里的call返回的值,如果call方法里面是耗时任务,则get方法会阻塞主线程。

代码实现如下:
TestCallable类:

package com.yds.test;

import java.util.concurrent.Callable;

public class TestCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        // TODO 自动生成的方法存根
        int i=0;
        while(i<10){
            System.out.println(i);
            Thread.sleep(1000);
            i++;
        }
        return i;
    }

}

Test调用

package com.yds.test;

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

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
        TestCallable testCallable = new TestCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
        Thread thread = new Thread(task);
        thread.start();     
    }

}

2.3 继承Thread类来创建线程

  • 步骤1:定义一个继承Thread类的子类
public class TestThread extends Thread{
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        
    }
}
  • 步骤2:构造子类的一个对象
TestThread testThread = new TestThread();
  • 步骤3:启动线程
testThread.start();

代码示例如下:

TestThread类

package com.yds.test;

public class TestThread extends Thread{
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        int i = 0;
        while(i<10){
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            i++;
        }
    }
}

Test调用

package com.yds.test;

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

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
        TestThread testThread = new TestThread();
        testThread.start();
        
        
    }

}

2.4 使用Executor框架来创建线程池

Executors类中包含以下四个创建线程池方法。

方法名 描述
newCachedThreadPool() 创建一个可以缓存的线程池,如果线程池中有线程可用,则复用该线程,如果线程不可用,则创建一个新的线程并加入线程池中。终止并从缓存池中移除那些60秒未被使用的线程。
newFixedThreadPool 创建固定数目线程的线程池。
newSingleThreadExecutor 创建一个单线程化的Executor
newScheduledThreadPool 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
  • Executor执行Runnable任务
package com.yds.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
//      TestThread testThread = new TestThread();
//      testThread.start();
        
        // 4. 使用Executor执行Runnable创建线程
        ExecutorService executorServicec = Executors.newCachedThreadPool();
        executorServicec.execute(new TestRunnable());
        executorServicec.shutdown();
        
    }

}

  • Executor执行Callable创建线程
package com.yds.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Test {

    public static void main(String[] args) {
        
        //1. 使用实现Runnable接口创建线程
//      Runnable testRunnable = new TestRunnable();
//      Thread testThread = new Thread(testRunnable);
//      testThread.start();
        
        
        //2. 使用Callable和Future创建线程
//      TestCallable testCallable = new TestCallable();
//      FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
//      Thread thread = new Thread(task);
//      thread.start();
        
        
        //3. 继承Thread创建线程
//      TestThread testThread = new TestThread();
//      testThread.start();
        
        // 4. 使用Executor执行Runnable创建线程
//      ExecutorService executorServicec = Executors.newCachedThreadPool();
//      executorServicec.execute(new TestRunnable());
//      executorServicec.shutdown();
        
        //5. 使用Executor执行Callable创建线程
        ExecutorService executorServicec = Executors.newCachedThreadPool();
        TestCallable testCallable = new TestCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(testCallable);
        
        executorServicec.execute(task);
        
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容