天天看点

线程中的同步(synchronized)的解释和例子

package synh;

class ThreadDemo implements Runnable{

 int tickets = 100;//票数

 String str = new String("");

 //在一个方法里实现同步

 public void run(){

  while(true){

   sale();

  }

 }

 public synchronized void sale(){

  if(tickets > 0){

     try{Thread.sleep(1);}catch(Exception e){}//模拟不同步的实现

     System.out.println(Thread.currentThread().getName() + " is salling ticket --- " + tickets--);

    }

 }

}

class ThreadTest{

 public static void main(String [] args){

  ThreadDemo td = new ThreadDemo();

  new Thread(td).start();

  new Thread(td).start();

  new Thread(td).start();

  new Thread(td).start();

 }

看完了线程间的同步,再看看同步方法和同步代码块之间的同步

package synch;

class ThreadDemo implements Runnable{

 int tickets = 100;//票数

 String str = new String("");

 //在一个方法里实现同步

 public void run(){

  if(str.equals("method")){

   while(true){

    sale();

   }

  }

  else{

   while(true){

    synchronized(this){

     if(tickets > 0){

      try{Thread.sleep(1);}catch(Exception e){}

      System.out.println(Thread.currentThread().getName() + " is salling ticket --- " + tickets--);

     }

    }

   }

  }

 }

 public synchronized void sale(){

  if(tickets > 0){

     try{Thread.sleep(1);}catch(Exception e){}//模拟不同步的实现

     System.out.println("method: " + Thread.currentThread().getName() + " is salling ticket --- " + tickets--);

    }

 }

}

class ThreadTest1{

 public static void main(String [] args){

  ThreadDemo td = new ThreadDemo();

  new Thread(td).start();

  //这里写这个sleep()是为了让CPU转到当前线程来执行

  try{Thread.sleep(1);}catch(Exception e){}  td.str = "method";

  new Thread(td).start();

  //new Thread(td).start();

  //new Thread(td).start();

 }

}

这里最关键的一点就是要想让同步方法和同步代码块同步,两者就要使用相同的监视器对象

本程序中用的同一个监视器对象是this