在Java中,一旦线程的start()方法被调用了一次,就不能再次调用start()方法。如果尝试多次调用start()方法,会抛出IllegalThreadStateException异常。
如果需要多次执行某个线程的任务,可以考虑以下两种解决方法:
public class MyThread extends Thread {
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start();
MyThread thread2 = new MyThread();
thread2.start();
// 可以创建更多的新线程对象并调用start()方法
}
}
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
// 可以创建更多的新线程对象并调用start()方法
}
}
无论是使用继承Thread类还是实现Runnable接口,都可以实现多次执行线程任务的效果。
上一篇:不能调节ubuntu分辨率
下一篇:不能调用子窗口函数