1.创建一个类继承Thread类,重写run()方法
将一个类声明为Thread的子类。 这个子类应该重写Thread类的方法run()。
- MyThread 类
public class MyThread extends Thread{
//重写run()方法
@Override
public void run() {
for (int i=0; i<10; ++i){
System.out.print(i + "\t");
}
}
}
- Test类
public class Test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
//Output:
// 0 1 2 3 4 5 6 7 8 9
在启用线程的使用要调用start()方法才算是开辟新线程,run()方法只是声明了一个任务而已,调用start()方法后使得使得线程进入就绪状态,待该线程抢到CPU时间片后就会执行本线程的run()方法。
如果单纯的调用run()方法,我们只不过是调用了一个顺序执行的任务而已。
2.实现Runnable接口中的run()方法并传入Thread类的构造器
创建一个Runnale接口的实现类,或者使用匿名内部类,也可以使用Lambda表达式,将他们传入Thread类的构造器,并调用run()方法。下面的代码展示了这三种方法;
//这是Runnable接口的实现类
class MyThread implements Runnable{
@Override
public void run() {
for (int i=0; i<10; ++i){
System.out.println(i);
}
}
}
public class Test {
public static void main(String[] args) {
//1.这里是用将一个Runnable实现类传入Thread构造器
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
//2.这里是使用匿名内部类实现Runnable接口
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i=0; i<10; ++i){
System.out.println(i);
}
}
};
Thread thread2 = new Thread(runnable);
//3.这里是使用Lambda表达式
Runnable r = () -> {
for (int i=0; i<10; ++i){
System.out.println(i);
}
};
Thread thread3 = new Thread(r);
thread1.start();
thread2.start();
thread3.start();
}
}
我个人觉得用Lambda表达式更简单,因为Lambda表达式允许将一段方法当作参数传入构造器:
Thread thread4 = new Thread( () -> {
for (int i=0; i<10; ++i){
System.out.println(i);
}
});
thread4.start();
在我之前的博客中粗略的介绍了Lambda表达式