Java创建线程的三种方法

导读:本篇文章讲解 Java创建线程的三种方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Java创建线程的三种方法

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口

方法一:继承Thread类

  • 自定义线程类继承Thread类
  • 重写run()方法,编写线程执行体
  • 创建线程对象,调用start()方法开启线程
// 自定义线程类继承Thread类
public class TestThread1 extends Thread {
    private String threadName;

    public TestThread1(String threadName) {
        this.threadName = threadName;
    }
	// 重写run()方法,编写线程执行体
    public void run() {
        //线程体
        for (int i = 0; i < 20; i++) {
            System.out.println(threadName + i);
        }
    }

    public static void main(String[] args) {
	//创建线程对象,调用start()方法开启线程
        //创建线程对象一
        TestThread1 testThread11 = new TestThread1("我是线程一");
        //调用Start方法开启线程
        testThread11.start();
        //创建线程对象二
        TestThread1 testThread12 = new TestThread1("我是线程二");
        //调用Start方法开启线程
        testThread12.start();

    }
}

方法二:实现Runnable接口

  • 定义MyRunnable类实现Runnable接口
  • 实现Run()方法,编写线程执行体
  • 创建线程对象,调用start()方法开启线程
public class TestThread2 implements Runnable {
    private String threadName;
    public TestThread2(String threadName){
        this.threadName=threadName;
    }
    public void run(){
        //线程体
        for (int i = 0; i < 20; i++) {
            System.out.println(threadName+i);
        }
    }

    public static void main(String[] args) {
        //创建Runnable接口的实现类对象
        TestThread2 testThread21=new TestThread3("我是线程一");
        TestThread2 testThread22=new TestThread3("我是线程二");
        //通过线程对象来开启线程
        new Thread(testThread21).start();
        new Thread(testThread22).start();
    }
}

方法三:实现Callable接口

  • 实现Callable接口,需要返回值类型
  • 重写call方法,需要抛出异常
  • 创建目标对象
  • 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
  • 提交执行:Future< Boolean> result1 = ser.submit(t1);
  • 获取结果:boolean r1=result1.get()
  • 关闭服务:ser.shutdownNow();
import java.util.concurrent.*;

public class TestThread4 implements Callable<Boolean> {
    private String threadName;

    public TestThread4(String threadName) {
        this.threadName = threadName;
    }

    public Boolean call() {
        //线程体
        for (int i = 0; i < 30; i++) {
            System.out.println(threadName + i);
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestThread4 t1 = new TestThread4("线程一");
        TestThread4 t2 = new TestThread4("线程二");
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(2);
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        //关闭服务
        ser.shutdownNow();

    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/5040.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!