Following # ①
Since ① is a method of inheritance, there are various inconveniences in use. Instead, method (2) will be used more often when creating threads.
Method (2): Create a thread using a class that implements the Runnable interface
As a step:
-Create a subclass that implements the runnable interface -Override of run () method -Instantiate the created runnable class -Create a new Thread instance with the Thread constructor using the generated runnable instance as an argument. -Call the start () method on the Thread instance
I actually wrote it: public class ThreadTest2 implements Runnable{
@Override
public void run(){
for (int i = 0; i < 5; i++){
System.out.println ("Print from new thread"); } } }
public class Sample2 {
public void main (String[] args){
ThreadTest2 th1 = new ThreadTest2();
Thread thread = new Thread(th1);
thread.start();
}
}
The point here is Thread thread = new Thread(th1);
The above code is a method to create a new thread by using the constructor of Thread class. A new Thread class can be created by using a class that implements the runnable interface as an argument.
Thread(Runnable target) Assign a new Thread object.
If the Thread class can be newly created, the rest is the same as ①, just start the thread with the start () method and let the scheduler execute it.
Recommended Posts