java进阶之多线程一创建线程

创建多线程的有三种方式

一 继承Thread 重写run 方法

class Test01{
    public static void main(String[] args) {
        myTh myTh = new myTh();
        myTh.start();
    }
}


//1 继承 Thread 重写 run 方法
class myTh extends  Thread{

    @Override
    public void run() {
        //获取线程名
        System.out.println(Thread.currentThread().getName()+"执行了");
        try {
            //延迟100 毫秒
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

实现 runnable 接口

class Test01{
    public static void main(String[] args) {
        long f = System.currentTimeMillis();
//-------------------------------------------------------
        RTh rth = new RTh();
        new Thread(rth).start();
//-------------------------------------------------------
        long h = System.currentTimeMillis();
        System.out.println(h-f);
    }
}



//2 实现 runnable 接口
class RTh implements  Runnable{

    @Override
    public void run() {
        //获取线程名
        System.out.println(Thread.currentThread().getName()+"执行了");
        try {
            //延迟100 毫秒
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

实现callable接口 创建带有返回值的线程

class Test01{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long f = System.currentTimeMillis();
//-------------------------------------------------------
        Cth cth = new Cth();

        FutureTask<String> tsk = new FutureTask<String>(cth);
        FutureTask<String> tsk2 = new FutureTask<String>(cth);
        //新建一个线程运行
        new Thread(tsk).start();
        new Thread(tsk2).start();
        System.out.println(tsk.get());  //等待返回 未返回 会阻塞 主线程 之后才会继续执行
        System.out.println("11111");
        System.out.println(tsk2.get());


//-------------------------------------------------------
        long h = System.currentTimeMillis();
        System.out.println(h-f);
    }
}



//3 实现callable 接口 形成带有返回值的线程
class Cth implements Callable<String> {


    @Override
    public String call() throws Exception {
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"执行了");
        return "我执行完了";
    }
}

在这里插入图片描述

注意: 如果 fultertask 在主线中使用 总耗时取决于耗费时间最长的线程 将会阻塞主线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值