Creating threads in Java

There are in general two ways to create and start a new thread in Java.

1. extend the Thread class and override the run() method

public class MyThread extends Thread{
    @Override
    public void run(){
        //define your task here
    }
}

2. implement the Runnable interface

public class MyRunnable implements Runnable{
    @Override
    public void run(){
        //define your task here
    }
}

Then how to start a new thread

For the first way

MyThread thread = new MyThread();
thread.start(); //start will eventually call the run() method of the Thread instance

For the second way

MyRunnable runnable = new MyRunnable();
new Thread(runnable).start(); //start will eventually call the run() method of the MyRunnable instance

In fact, if we check the source of the Thread class, it will be something like this

public class Thread implements Runnable{
     private Runnable target;
     public Thread(Runnable tar){
         this.target = tar;
     } 
     public void start(){
         // some magic code which will eventually call run() 
     }
     public void run(){
         if(this.target != null){
             this.target.run();
         }
     }
}
Now we can understand the two ways of creating threads, the first way simply uses runtime polymorphism, and the second way is even more straightforward.


Note: Please do not directly call thread.run() or runnable.run() if you expect some parallel execution. As the direct calls will make the code synchronously executed in the current thread, in fact the MyThread and MyRunnable are simply two classes with nothing special. There are some pieces of code in the Thread.start() which can magically create new threads.




猜你喜欢

转载自blog.csdn.net/Andrew659/article/details/7566452