在Java中,有两种主要的方式来创建线程:
示例代码如下:
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
示例代码如下:
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
无论是实现Runnable接口还是继承Thread类,都可以创建线程。但通常推荐使用实现Runnable接口的方式,因为Java不支持多重继承,如果一个类已经继承了其他类,就无法再继承Thread类来创建线程,而实现Runnable接口则没有这个限制。