多线程的实现方式

1.继承Thread,重写run方法

class ThreadExt extends Thread {
    @Override
    public void run() {
        System.out.println("多线程"+this.getName());
        try{
            sleep(1000L);
            System.out.println("多线程"+this.getName()+"睡眠结束");
        }catch (Exception e) {

        }
    }
}

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

class ThreadImpRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("Runnable start");
        try{
            Thread o = new Thread();
            o.sleep(3000L);
            System.out.println("Runnable睡眠结束");
        }catch (Exception e) {

        }
    }
}

3.实现Callable接口,重写call方法

class ThreadImpCallable implements Callable<String>{
    @Override
    public String call()  throws Exception{
        System.out.println("Callable start");
        try{
            Thread o = new Thread();
            o.sleep(3000L);
            System.out.println("Callable睡眠结束");
        }catch (Exception e) {

        }
        return "callable返回值";
    }

}

主线程如何调用

public class ThreadExtend {

    public static void main(String[] args) throws Exception{
    	//1 继承Thread
        System.out.println("主线程开始");
        ThreadExt threadExtend =  new ThreadExt();
        threadExtend.start();
        
		//2 实现Runnable接口
        Long start1 = System.currentTimeMillis();
        Thread thread = new Thread(new ThreadImpRunnable());
        thread.start();
        System.out.println("runnable执行花了"+(System.currentTimeMillis()-start1));

		//3 实现Callable接口
        Long start = System.currentTimeMillis();
        ThreadImpCallable callableDemo = new ThreadImpCallable();
        FutureTask futureTask = new FutureTask<>(callableDemo);
        Thread threadcall = new Thread(futureTask);
        threadcall.start();
        System.out.println("callable开始执行花了"+(System.currentTimeMillis()-start));
        String name = (String) futureTask.get(); //获取返回值
        System.out.println(name);
        System.out.println("callable执行完得到结果花了"+(System.currentTimeMillis()-start));

    }
}

结论

3种多线程方式执行start之后,都是以多线程的方式同时开始的,但Callable接口想要获取返回值,需要阻塞到方法执行完

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值