如果我们在start方法而不是run方法中执行整个Thread功能会发生什么?下面的代码运行方式与在run方法中添加代码时运行的方式相同...
public class RunMethodTest extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Abc abc=new Abc();
abc.start();
}
}
class Abc extends Thread
{
@Override
public synchronized void start() {
super.start();
for(int i=0;i<10;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread" + " " + i);
}
}
}
答案 0 :(得分:1)
测试它:让你的代码通过
告诉你它正在调用哪个线程Thread.currentThread()
getId()
和getName()
public class ThreadTest {
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
System.out.printf("Main, Which Thread: %s, %d%n",
currentThread.getName(),
currentThread.getId());
Abc abc = new Abc();
abc.start();
}
}
class Abc extends Thread {
@Override
public synchronized void start() {
super.start();
Thread currentThread = Thread.currentThread();
System.out.printf("Start, Which Thread: %s, %d%n",
currentThread.getName(),
currentThread.getId());
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread" + " " + i);
}
}
@Override
public void run() {
super.run();
Thread currentThread = Thread.currentThread();
System.out.printf("Run, Which Thread: %s, %d%n",
currentThread.getName(),
currentThread.getId());
}
}
对我来说,这会返回:
Main, Which Thread: main, 1
Start, Which Thread: main, 1
Run, Which Thread: Thread-0, 9
Thread 0
Thread 1
Thread 2
Thread 3
....
这证明你的Abc的start方法(正如预期的那样)在与调用代码相同的线程中调用而不是在新线程中调用,并且只有run()
方法中的代码在新的内部被调用线。如上所述,您几乎从不需要或想要扩展Thread,而是实现Runnable或Callable。