继承Thread类:
创建一个类,继承自Thread
类,并重写run()
方法来定义线程的任务。然后实例化这个类的对象并调用start()
方法启动线程。
class MyThread extends Thread {
public void run() {
// 线程任务
}
}
// 创建线程对象并启动
MyThread thread = new MyThread();
thread.start();
实现Runnable接口:
创建一个实现了Runnable
接口的类,并实现接口中的run()
方法来定义线程的任务。然后将这个实现了Runnable
接口的对象传递给Thread
类的构造函数,并调用start()
方法启动线程。
class MyRunnable implements Runnable {
public void run() {
// 线程任务
}
}
// 创建线程对象并启动
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
使用匿名内部类:
可以直接在创建线程时使用匿名内部类来实现Runnable
接口或扩展Thread
类。
// 使用匿名内部类实现Runnable接口
Runnable runnable = new Runnable() {
public void run() {
// 线程任务
}
};
Thread thread = new Thread(runnable);
thread.start();
// 使用匿名内部类扩展Thread类
Thread thread = new Thread() {
public void run() {
// 线程任务
}
};
thread.start();