三种创建线程的方法

目录

实现Runnable接口

继承Thread

通过FuturerTask和Callable


 

实现Runnable接口

  public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {//这里采用了匿名函数的方式,可以写一个类实现接口Runnable,new MyRunnable(){}
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
                }
            }).start();

        }
    }

 

继承Thread

 public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new MyThread().run();
        }

            }
    static class MyThread extends Thread{//Thread实现了Runable接口
       @Override
       public void run() {
           System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
       }
   }

通过FuturerTask和Callable

 

public static void main(String[] args) throws ExecutionException, InterruptedException {
        for (int i = 0; i < 100; i++) {
            new Thread(new FutureTask<>(new Callable<Integer>() {//FutureTask实现了Runnable接口
                @Override
                public Integer call() throws Exception {
                    System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
                    return 1;
                }
            })).start();
        }
    }

 

拓展:lambda表达式

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Runnable是函数式接口:函数式接口都可以使用lambda表达式和函数式引用简化:

new Thread(ThreadTest::incre).start();//Runnable调用run=ThreadTest的incre
new Thread(() -> { System.out.println("hello world");//Runnable调用run=输出一句话helloWorld}).start();

可以这么理解:如果传入的是函数式接口对象参数,那么就只着眼于里面的唯一抽象方法怎么做就好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值