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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值