Java中如何产生一个线程

本文介绍了Java中实现多线程的三种方式:通过继承Thread类、实现Runnable接口以及使用Callable和Future。每种方式都有详细的代码示例,展示了如何创建和启动线程以及获取线程执行结果。
摘要由CSDN通过智能技术生成

1.通过继承 Thread 类,重写run方法

    public class Text extends Thread {
    public void run() {
        for (int i = 0; i < 101; i++) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + ":" + i);
        }
    }

    public static void main(String[] args) {
        Text text = new Text();
        Text text1 = new Text();
        text.start();
        text1.start();
    }
}

2.通过实现 Runnable 接口,重写run方法

public class Text1 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 101; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }

    public static void main(String[] args) {
        Text1 text1 = new Text1();
        Text1 text2 = new Text1();
        //产生俩个线程去包装这两个任务text1,text2
        //新建状态
        Thread thread = new Thread(text1);
        Thread thread1 = new Thread(text2);
        thread.start();
        thread1.start();
    }
}

3.通过 Callable 和 Future 创建线程

a)创建 Callable 接口的实现类,并实现 call()方法,该 call()方法将作为 线程执行体,并且有返回值(类似于 run()方法)。

b)创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象, 该 FutureTask 对象封装了该 Callable 对象的 call()方法的返回值。

c)使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。

d)调用 FutureTask 对象的 get()方法来获得子线程执行结束后的返回值。

public class Text2 implements Callable {
    @Override
    //重写call方法,这个方法有返回结果,其它跟run方法一致
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 101; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
            sum += i;
        }
        return "1-100之和:" + sum;
    }

    public static void main(String[] args) throws Exception {
        Text2 text2 = new Text2();
        Text2 text3 = new Text2();
        FutureTask fu1 = new FutureTask(text2);
        FutureTask fu2 = new FutureTask(text3);
        Thread t1 = new Thread(fu1);
        Thread t2 = new Thread(fu2);
        t1.start();
        t2.start();
        //获取到返回结果
        Object result1 = fu1.get();
        Object result2 = fu2.get();
        System.out.println(result1);
        System.out.println(result2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

夙愿-妍

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

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

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

打赏作者

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

抵扣说明:

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

余额充值