上一篇 synchronized 的寫法, 其實只是為了說明而以, 事實上, 我們並不會這麼寫. 因為t2會在500ms~1000ms之間, 持續進入running區, 但因為沒有鑰匙不得其門而入再退出, 所以一直在running 及runnable之間徘迴浪費CPU資源.
我們改用下面的方法, 在t2之間加入t1.join(); 即跟自已(t2)講, 要禮讓t1先執行, 待t1執行完畢, 才會啟動自已. 如果就不會浪費CPU的資源了
public class JavaApp{
public static void main(String[] args) {
Pikachu p=new Pikachu();
Thread t1=new Thread(new Runnable(){
@Override
public void run() {p.setLevel(100);}
});
Thread t2=new Thread(new Runnable(){
@Override
public void run() {
try {t1.join();} catch (InterruptedException ex) {}
System.out.printf("皮卡丘的等級為 : %d\n", p.getLevel());
}
});
t1.start();
t2.start();
}
}
class Pikachu{
private int level;
public void setLevel(int level){
try {Thread.sleep(1000);}catch (InterruptedException ex) {}
this.level=level;
}
public int getLevel(){
return level;
}
}
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.