Question 122
Given:
1. public class TestOne implements Runnable {
2. public static void main (String[] args) throws Exception {
3. Thread t = new Thread(new TestOne());
4. t.start();
5. System.out.print(“Started”)
6. t.join();
7. System.out.print(“Complete”)
8. }
9. public void run() {
10. for (int i= 0; i< 4; i++) {
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints “StartedComplete”
D. The code executes and prints “StartedComplete0123”
E. The code executes and prints “Started0l23Complete”
Answer: E
这是什么原理啊??????????
我认为的是t.start()调用run()之后,应先运行run()的方法中定义的操作,也就是先输出:0123,然后再输出Started和Complete.我想答案应该就是: 0123StartedComplete.可为什么是E????谢谢...
Given:
1. public class TestOne implements Runnable {
2. public static void main (String[] args) throws Exception {
3. Thread t = new Thread(new TestOne());
4. t.start();
5. System.out.print(“Started”)
6. t.join();
7. System.out.print(“Complete”)
8. }
9. public void run() {
10. for (int i= 0; i< 4; i++) {
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints “StartedComplete”
D. The code executes and prints “StartedComplete0123”
E. The code executes and prints “Started0l23Complete”
Answer: E
这是什么原理啊??????????
我认为的是t.start()调用run()之后,应先运行run()的方法中定义的操作,也就是先输出:0123,然后再输出Started和Complete.我想答案应该就是: 0123StartedComplete.可为什么是E????谢谢...
还会继续执行的,这就要看系统怎么分配cpu了。
考虑到下面的语句(标红色)
t.join();
System.out.print(“Complete”)
所以System.out.print(“Complete”) 肯定在run执行完以后才能执行
这个join是由t来调用的啊,怎么会使主线程让出呢 ??t.join(),不就是让自己定义的线程t Waits for this thread to die 吗?
Thread t = new Thread(new TestOne());
t.start();//启动负线程,运行run方法;
System.out.println("Started");
//主线程输出,这句与Thread t = new Thread(new TestOne())是同组的,所以他比较快一点;
t.join();//负线程等待
System.out.print("Complete");
join
public final void join()
throws InterruptedException
Waits for this thread to die. //请问是谁waits for this thread to die啊?这个谁也是个thread吗?Throws:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.