您的位置:首页 > 编程语言 > Java开发

Creating threads in Java

2012-05-14 21:25 337 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: