Java 创建线程的三种方式

Java 创建线程的多种方式

1. 继承 Thread 类(不推荐)

继承 Thread 类的方法:

public class Type1 {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        MyThread thread2 = new MyThread();
        
        thread.start();
        thread2.start();
        
        System.out.println(thread);
        System.out.println(thread2);
    }
}


/**
 * 1. 继承 Thread 类
 */
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.print(i + " ");
        }
    }
}

这种方法有个缺点,因为 Java 只能单继承,所以如果如果只要继承了 Thread 类,就不能再继承其他类了,失去了可扩展性。

Java 可以实现继承和实现,若继承了 Thread 就无法继承其他类了:

class Test extends Object implements TestIn {}

2. 实现 Runnable 接口

实现 Runnable 接口方法:

public class Type2 {

    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread(), "task1");
        Thread thread2 = new Thread(new MyThread(), "task2");

        thread.start();
        thread2.start();

        System.out.println(thread);
        System.out.println(thread2);
    }

}

/**
 * 2. 实现 Runnable 接口
 */
class MyThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.print(i + " ");
        }
    }

}

实现 Runnable 接口,这样解决了继承 Thread 所带来的缺点。用实现 Runnable 的类去初始化 Thread 即可。

3. 实现 Callable 接口

Runnable 接口无法实现的功能:当线程终止时(即 run() 完成时),我们无法使线程反回结果。为了支持此功能,Java 中提供了 Callable 接口。

  • 实现 Callable 接口的 call() 方法,可以抛出异常,并且具有返回值。

Runnable 接口有个实现类 FutureTaskFutureTask 构造可以传递实现 Callable 接口的对象。

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

public class Type3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> task1 = new FutureTask<>(new MyThread());
        FutureTask<Integer> task2 = new FutureTask<>(()->{
            int s = 0;
            for (int i = 1; i <= 100; i++) {
                s += i;
            }
            System.out.println(Thread.currentThread().getName() + " completed!");
            Thread.sleep(1000);
            return s;
        });

        Thread thread = new Thread(task1, "t1");
        Thread thread2 = new Thread(task2, "t2");

        thread.start();
        thread2.start();

        while (!task1.isDone()) {
            System.out.println("task1 waiting....");
        }


        System.out.println(task1.get());
        System.out.println(task2.get());
        System.out.println(Thread.currentThread().getName() + " completed!");
    }
}


class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int s = 0;
        for (int i = 1; i < 200; i++) {
            s += i;
        }
        System.out.println(Thread.currentThread().getName() + " completed!");
        return s;
    }
}

在这里插入图片描述

附录

可以设置优先级 [1-10],默认为 5,10 优先级最高。

计算代码运行时间:

long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
System.out.println("共耗时"+ (end - start) +"毫秒");
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哇咔咔负负得正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值