Java创建线程的三种方式

1、继承Thread然后重写run方法(没有返回值)

package com.ws;

public class Demo01 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        for (int i = 0; i < 10; i++) {
            System.out.println("主线程->"+i);
        }

    }
}

class MyThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("分支线程->"+i);
        }
    }
}

2、实现Runnable接口,重写run方法(没有返回值)

package com.ws;

public class Demo02 {

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("主线程"+i);
        }
    }

}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("分支线程"+i);
        }
    }
}

3、实现Callable接口重写call方法(有返回值)

package com.ws;

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

/**
 * 实现线程的第三种方式:
 *      实现Callable接口
 * 这种方式的优点:可以获取到线程的执行结果
 * 这种方式的缺点:效率比较低,在获得t线程执行结果的时候,当前线程受阻塞,效率低。
 */

public class Demo03 {
    public static void main(String[] args) throws Exception{
        //第一步:创建一个”未来任务类“对象
        FutureTask task = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {//call()方法就相当于run方法

                System.out.println("call method begin!!!");
                Thread.sleep(10000);
                System.out.println("call method end!!!");
                int a = 100;
                int b = 200;
                return a + b;//自动装箱(300结果变成Integer)

            }
        });
        //创建线程对象
        Thread t = new Thread(task);
        //启动线程
        t.start();
        //在这里是main方法
        //在主线程中怎么获取t线程的返回值
        Object o = task.get();
        System.out.println("线程执行结果:"+o);


        //main方法这里的程序要想执行必须等待get()方法的结束
        //而get()方法可能需要很久,因为get()方法是为了拿到另一个线程的执行结果
        //而另一个线程执行是需要时间的
        System.out.println("Hello!!!");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

快醒醒鸭今天你编程了吗?

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

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

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

打赏作者

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

抵扣说明:

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

余额充值