Java实现多线程有两种途径:继承Thread类和实现Runnable接口。
示例代码如下:
public class MyThread extends Thread {
@Override
public void run() {
// 线程的任务
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
示例代码如下:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程的任务
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
区别: