java 为什么要选择个?

来源:百度知道 编辑:UC知道 时间:2024/06/07 11:15:21
public class Exercise extends Thread{
private String name;

public static void main(String[] args){
Exercise ex = new Exercise();
ex.go();
}

Exercise(){}

Exercise(String name){
super(name);
}

public void go(){
Exercise first = new Exercise("first");
first.start();

Exercise second = new Exercise("second");
second.start();
}

public void start(){
for(int i = 0; i < 2; i ++){
System.out.print(getName() + i + " ");

try{
Thread.sleep(100);
} catch(InterruptedException e){}
}
}
}

在编译或运行时下列说法哪一个是正确的?( 2 )
(1) 编译时引发异常
(2) 编译通过并可能输出“first0 first1 second0 second1”
(3) 编译通过并可能输出“first0 second0 first1 second1”
(4) 运行时引发异常

第一次进入该程序时
先进入到main函数.

执行
public void go(){
Exercise first = new Exercise("first");
first.start();

Exercise second = new Exercise("second");
second.start();
}
这个方法

先执行到first.start();

public void start(){
for(int i = 0; i < 2; i ++){
System.out.print(getName() + i + " ");

try{
Thread.sleep(100);
} catch(InterruptedException e){}
}

该方法每次进入的时候,都会执行两次.
第一次进入,i=0,第二次进入,i=1
当第三次i=2时,因条件不满足,所以跳出循环

也就是说,他会执行两次
System.out.print(getName() + i + " ");

因为,第一次是 first.start();
所以,getName的值就等于 "first",而i 的值就两个,一个是0,一个是1

上面说了,它会执行两次,所以就会出来first0 first1

接着才执行到 second.start();

这样说,能明白吗?

基本的java线程啊

Exercise(){}

Exercise(String name){
super(name);
}

首先这个写法肯定不对。Exercise(){} 大括号不应该括死。