天天看点

Java SE -- 多线程 线程安全问题解决

package thread;

class ThreadTest3 implements Runnable{

 private 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(10);                                                                   

     }catch(Exception e) {

      e.printStackTrace();

     }

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

    }

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

   }

  }

  } 

 }

 public synchronized void sale() {

  if(tickets>0){

   try{

    Thread.sleep(10);

   }catch(Exception e){

    e.printStackTrace();

   }

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

  }

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

 }

}

public class ThreadDemo6 {

 public static void main(String[] args) {

  ThreadTest3 t3=new ThreadTest3();

  new Thread(t3).start();

  try {

   Thread.sleep(10);

  } catch (InterruptedException e) {

   // TODO 自动生成 catch 块

   e.printStackTrace();

  }

  t3.str=new String("method");

  new Thread(t3).start();

 }

}