Java中创建多线程

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();

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

 

 

 
posted @ 2021-11-11 10:46  恩恩先生  阅读(122)  评论(0编辑  收藏  举报