It was a little difficult to create a new thread in Java, so I tried to summarize it myself.
Method (1): Inherit the Thread class to create a thread
The steps are as follows: -Create a subclass that inherits the Thread class -Override of run () method -Instantiate the created subclass -Call the start () method on the created instance
The inherited Thread class is a class that implements the Runnable interface. The documentation defines: public class Thread extends Object implements Runnable
*link: https://docs.oracle.com/javase/jp/8/docs/api/java/lang/Thread.html
I actually wrote it:
//Class to inherit
class ThreadTest1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Output from a new thread");
}
}
}
//Caller
public class Sample1 {
public static void main (String[] args){
//Instance generation
ThreadTest1 th = new ThreadTest1();
//start()Execute the method, spawn a thread and make it executable
th.start();
System.out.println("main thread ends");
}
}
Execution result:
【
main thread ends
Output from a new thread
Output from a new thread
Output from a new thread
Output from a new thread
Output from a new thread
】
☆ Point here: The run () method is not called directly, but if start () puts the newly created thread into an executable state and the scheduler puts it into an executable state, the run () method is executed. In other words, I thought I kicked a new thread with start (), but in fact it just started. The actual execution is left to the scheduler.
Recommended Posts