【java必看】创建线程的三种方法

1.实现Thread类是实现线程的创建 (两种)

2.实现Runnable接口的方式 (三种)

3.实现Callable接口的方式(一种)

1.实现Thread类是实现线程的创建线程 :

方式一:

 static  class MyThread extends Thread{
        @Override
        public void run() {
            //线程执行任务
            System.out.println("线程名称:"+Thread.currentThread().getName());
        }
    }

方式二:

 public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                System.out.println("线程名称:"+Thread.currentThread().getName());
            }
        };
        thread.start();

继承Thread类的方式的缺点:java语言的设计当中只能实现单继承,如果继承了Thread类,就不能继承其他类。(不常用)

2.实现Runnable接口的方式 (Java不能实现多继承但可以实现多接口):

方式三:

static class  MyRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println("线程名称:"+Thread.currentThread().getName());
        }
    }
    public static void main(String[] args) {
        //新建Runnable类
        MyRunnable runnable = new MyRunnable();
        //新建Thread类
        Thread thread = new Thread(runnable);
        //启动线程
        thread.start();
    }

方式四:

public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程名称:"+Thread.currentThread().getName());
            }
        });
        thread.start();
    }

方式五:

public static void main(String[] args) {
        Thread thread = new Thread(()->{
            System.out.println("线程名称"+Thread.currentThread().getName());
        });
        thread.start();
    }
3.实现Callable接口+Future容器的方式(创建并得到线程的执行结果)

方式六:

 static class Mycallable implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int num =new Random().nextInt(10);
            System.out.println("子线程名称:"+Thread.currentThread().getName()+",随机数"+num);
            return num;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Mycallable mycallable = new Mycallable();
        //创建一个FutureTask对象来接受返回值
        FutureTask<Integer> futureTask = new FutureTask<>(mycallable);
        Thread thread = new Thread(futureTask);
        thread.start();
         int result  = futureTask.get();
        System.out.println(String.format("线程名,%s,数字:%d",Thread.currentThread().getName(),result));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值