您的位置:首页 > 编程语言 > Java开发

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

2009-12-03 21:54 405 查看
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();
 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息