Java Thread Creation Using Thread Class
In Java, creating a thread using the Thread class can be achieved by following these steps:
- Create a class that extends the Thread class, override the run() method, and write the thread’s execution logic within the run() method.
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行逻辑
System.out.println("Hello, I am a thread!");
}
}
- Create a thread object in the main program and call the start() method to start the thread.
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
By following the steps above, you can create a thread using the Thread class and execute the thread logic. It is important to note that a thread object can only call the start() method once to start the thread, as calling it again will result in an IllegalThreadStateException being thrown.