java 多线程编程系列之2----线程的创建和启动方式

启动线程的5种方法:

1. new MyThread().start()

2. new Thread(r).start()

3. new Thread(lamda).start()

4. ThreadPool...

5. Future Callable and FutureTask


示例:

import java.util.concurrent.*;

public class T02_HowToCreateThread {

    static class MyThread extends Thread {

        @Override

        public void run() {

            System.out.println("Hello MyThread!");

        }

    }

    static class MyRun implements Runnable {

        @Override

        public void run() {

            System.out.println("Hello MyRun!");

        }

    }

    //带返回值的线程

    static class Mycall implements Callable<String>{

        @Override

        public String call() throws Exception {

            System.out.println("hello mycall");

            return "success";

        }

    }

//启动线程的5种方式

public static void main(String[] args) throws Exception{

//第1 种启动线程

        new MyThread().start();

//第2种启动线程

        new Thread(new MyRun()).start();

//第3种启动线程

        new Thread(()->{

            System.out.println("Hello Lambda!");

        }).start();

        

        //第4 线程池的方式启动线程

        ExecutorService service = Executors.newCachedThreadPool();

        service.execute(()->{

            System.out.println("hello threadpool");

        });

       //第5.1 带返回值的线程,利用线程池来执行

        Future<String> future = service.submit(new Mycall());

        future.get();//这个方法是阻塞的,获取返回值

       //第5.2.1 带返回值的线程,利用FutureTask来执行的第一种写法

        FutureTask<String> task = new FutureTask<>(new Mycall());

        Thread thread = new Thread(task);

        thread.start();

        System.out.println(task.get());//获取返回值

        //第5.2 2带返回值的线程,利用FutureTask来执行的第二种写法

        Thread t = new Thread(new FutureTask<String>(new Mycall()));

        t.start();

        service.shutdown();

    }

}

 这么多种启动线程的方式,其实本质上及是new 一个Tread对象,底层代码都是这样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值