Java中创建新线程有多种方式,一般从Thread派生一个自定义类,然后覆写run方法,或者创建Thread实例时,传入一个Runnable实例。两种方式可通过内部匿名类或者lambda语法进行简写。

1、通常写法

class MyTheard extends Thread {
    @Override
    public void run() {
        System.out.println("new thread created by extends thread");
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("new thread created by implements runnable");
    }
}
Thread t1 = new MyTheard();
Thread r1 = new Thread(new MyRunnable());
t1.start();
r1.start();

2、使用内部匿名类简写

Thread t2 = new Thread() {
    @Override
    public void run() {
        System.out.println("new thread created by extends thread using Anonymous class");
    }
};

Runnable r2 = new Runnable() {
    @Override
    public void run() {
        System.out.println("new thread created by implements runnable using Anonymous class");
    }
};
t2.start();
new Thread(r2).start();

3、使用lambda语法

Thread t3 = new Thread(()-> {
    System.out.println("new thread created by extends thread using lambda");
});

Runnable r3 = ()-> {
    System.out.println("new thread created by implements runnable using lambda");
};
t3.start();
new Thread(t3).start();

 使用简化的语法,减少了代码量,并且无需定义子类名,解决了命名难的问题。

 

 

参考链接

https://www.liaoxuefeng.com/wiki/1252599548343744/1376414781669409

相关文章:

  • 2021-09-17
  • 2021-06-10
  • 2021-11-01
  • 2021-11-20
  • 2021-09-04
  • 2021-11-27
  • 2022-01-01
  • 2021-11-22
猜你喜欢
  • 2022-01-01
  • 2021-12-18
  • 2021-07-27
  • 2021-10-28
  • 2022-02-09
  • 2022-12-23
相关资源
相似解决方案