我们该怎样创建一个线程,创建完线程后该怎样去运行一个线程呢?
创建一个线程有两种方式,第一种是从Thread类继承,Class Mythread extends thread,从Thread类继承,Thread继承之后重写run方法。第二种是你定义一个类去实现Runable接口,依然重写run方法,但是如果你用第二种方法,想让这个线程运行起来,必须newThread(new MyRun()).start();,然后呢,把我的实现Runable接口的这个类的对象new MyRun()传进来,然后再调用start。如果你是从Thread类继承的,那么你直接调用start就可以。需要注意的是,一定是要用start,而不是调用run。调用Thread还有第三种方式,其实也是第二种的一种变形。第三种就是使用Lambda表达式的方式,示例中thread()->{System.out.println "hello lambda!"}。
给大家看看下面的代码示例:
public class T02_HowtoCreateThread {
static class MyThread extends Thread{
public void run() {
System.out.println("Hello MyThread!");
}
}
static class MyRun implements Runnable{
public void run() {
System.out.println("Hello MyRun!");
}
}
public static void main (String[] args) {
//第一种方式
new MyThread().start();
//第二钟方式
new Thread(new MyRun()).start();
//第三种方式
new Thread(()->{
System.out.println("Hello Lambda!");
}).start();
}
}
有一道面试题:启动线程的三种方式
并不是上面的三种方式,而是第一种是从Thread继承,第二种是实现Runnable接口,第三种是通过线程池来启动Executors.newCachedThread,其实在这个线程池里面起线程的时候也是用的前两种方式之一。