各路大侠,下代码中,为什么注释和不注释会出现两种不同的结果。虽然 sleep 是个静态方法,但 java 允许用实例来调用,所以可以出现这样的写法,所以也请大侠们说一下这段代码的含义。谢谢!public class ThreadAsk { public static void main(String[] args) {
DThread t = new DThread();
DThread t2 = new DThread();
t.setName("t");
t2.setName("t2");
try{
t.start();
// 这句话注释前后有区别谁能解释下
t.sleep(1000);
t2.start();
}catch(InterruptedException ex){
System.out.println(ex.getMessage());
}
}}class DThread extends Thread{ public void run() {
int count = 0;
do{
try{
System.out.println(Thread.currentThread().getName());
Thread.sleep(100);
}
catch(InterruptedException ex){
count++;
}
count++;
}while(count < 10);
}
}
DThread t = new DThread();
DThread t2 = new DThread();
t.setName("t");
t2.setName("t2");
try{
t.start();
// 这句话注释前后有区别谁能解释下
t.sleep(1000);
t2.start();
}catch(InterruptedException ex){
System.out.println(ex.getMessage());
}
}}class DThread extends Thread{ public void run() {
int count = 0;
do{
try{
System.out.println(Thread.currentThread().getName());
Thread.sleep(100);
}
catch(InterruptedException ex){
count++;
}
count++;
}while(count < 10);
}
}
t
t
t
t
t
t
t
t
t
t
t2
t2
t2
t2
t2
t2
t2
t2
t2
t2注释的结果是
t
t2
t2
t
t2
t
t2
t
t2
t
t2
t
t2
t
t2
t
t2
t
t2
t
// 这句话注释前后有区别谁能解释下
t.sleep(1000);
t2.start();
DThread类其实只 sleep 了1/10 秒,
t 与 t2 只是 DThread类的两个实例对象,
,
t t 启动执行,sleep 一秒
t2 t2启动执行,
t2 t2执行, sleep 1/10秒
t t 执行 sleep 1/10秒
t2 t2执行,sleep 1/10秒
依次类推