javaSE基础编程——线程同步

 
  

编写程序模拟3个老师分发80份试卷,每个老师分发试卷为一个线程


package com.cissst.software.thread;

public class GivePaper implements Runnable {
 private int paper = 80;
 Object lock = new Object();
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(paper>0){
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   synchronized(lock){
    if(paper>0){
     System.out.println(Thread.currentThread().getName()
       +"正在发第"+paper+"张试卷");
     //发完一张减一张
     paper--;
    }
   }
  }
 }

}


package com.cissst.software.thread;

public class MainThread {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GivePaper givepaper = new GivePaper();
  new Thread(givepaper,"第一个老师").start();
  new Thread(givepaper,"第二个老师").start();
  new Thread(givepaper,"第三个老师").start();
 }

}





你可能感兴趣的:(javaSE基础)