?? machine.java
字號:
package synsleep;
public class Machine implements Runnable {
private int a=1; //共享數據
public void run() {
for(int i=0;i<1000;i++){
synchronized(this){
a+=i;
try{
Thread.sleep(500); //給其他線程運行的機會
}catch(InterruptedException e){throw new RuntimeException(e);}
a-=i;
System.out.println(Thread.currentThread().getName()+":"+a);
}
}
}
public void go(){
for(int i=0;i<1000;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.yield();
}
}
public static void main(String args[]) throws InterruptedException{
Machine machine=new Machine();
Thread t1=new Thread(machine);
Thread t2=new Thread(machine);
t1.start();
t2.start();
machine.go();
}
}
/****************************************************
* 作者:孫衛琴 *
* 來源:<<Java面向對象編程>> *
* 技術支持網址:www.javathinker.org *
***************************************************/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -