synchronized关键字

来源:互联网 发布:软件无线电原理与技术 编辑:程序博客网 时间:2024/05/22 16:05

//线程同步——synchronized关键字
package button2;
public class getmain implements Runnable{
 int num=10;
 public void run() {
  while(true) {
   synchronized("") {//解决资源共享问题,同步块,一个时段只允许一个访问
    if(num>0) {
     try {
      Thread.sleep(1000);
      
     }catch(Exception e){
      e.printStackTrace();
      
     }
     System.out.println("tickets"+--num);
     
    }
   }
  }
  
  }
 public static void main(String []args) {
  getmain t=new getmain();
  Thread ta=new Thread(t);
  Thread tb=new Thread(t);
  Thread tc=new Thread(t);
  Thread td=new Thread(t);
  ta.start();
  tb.start();
  tc.start();
  td.start();
 }
}除此之外,还可以将每一个方法设为sychronized

原创粉丝点击