从我在Java中使用线程的时间开始,我发现了这两种编写线程的方法:
用implements Runnable:
public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
Run Code Online (Sandbox Code Playgroud)
或者,用extends Thread:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
Run Code Online (Sandbox Code Playgroud)
这两个代码块有什么显着差异吗?
下面两个线程调用有什么区别?这两个电话会同样行事吗?
注意:我没有同时使用#1和#2,这是最好的选择.
private void startConnections(){
ServerThread server = new ServerThread();
server.start(); // #1
Thread serverThread = new Thread(server);
serverThread.start(); //#2
}
class ServerThread extends Thread{
public void run(){}
}
Run Code Online (Sandbox Code Playgroud)