⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 machine.java

📁 这是孙卫琴在"Java与面向对象编程"一书的源代码。
💻 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 + -