这是我的两个班级:
public class Firstclass {
public static void main(String args[]) throws InterruptedException {
System.out.println("Main start....");
Secondclass t1 = new Secondclass();
t1.setName("First Thread");
Secondclass t2 = new Secondclass();
t2.setName("Second Thread");
t1.start();
t2.start();
System.out.println("Main close...");
}
}
和
public class Secondclass extends Thread {
@Override
public void run() {
try {
loop();
} catch(Exception e) {
System.out.println("exception is" + e);
}
}
public void loop() throws InterruptedException {
for(int i = 0; i <= 10; i++) {
Thread t = Thread.currentThread();
String threadname = t.getName();
if(threadname.equals("First Thread")) {
Thread.sleep(1000);
} else {
Thread.sleep(1500);
}
System.out.println("i==" + i);
}
}
}
现在我跑的时候 Firstclass
然后输出是:
Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10
我的第一个问题是: 我想知道为什么两个线程仍在运行,即使它 main
方法已经完成?
我的第二个问题是: 任何人都可以向我解释方法之间的区别 join
和 synchronized
?