- 显式继承重写
//继承Thread并重写
public class Thread01 extends Thread {
//重写run方法
@Override
public void run() {
while (true) {
System.out.println("Thread test.");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//根据Thread01创建线程并启动
@Test
public void test1() {
Thread t1 = new Thread01("myName");
t1.start();
}
- 匿名类重写
//根据Thread提供的有参构造方法创建线程对象(构造方法的参数为一个方法)
new Thread(()->{ //这个匿名方法为run()方法
while (true) {
i.getAndIncrement();
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
//根据Thread提供的无参构造方法创建线程对象,然后重写run()方法
new Thread(){
@Override
public void run() {
while (true) {
i.getAndIncrement();
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();