黑马程序员技术交流社区

标题: 多线程——买票 [打印本页]

作者: yan1992924    时间: 2016-3-30 21:18
标题: 多线程——买票
package lianxi;
public class MaiPiao {
多线程的题希望对大家有帮助
/**


* @param args
  */
public static void main(String[] args) {
  Ticket tickets=new Ticket();
  Thread thread=new Thread(tickets,"张三");
  Thread thread2 =new Thread(tickets,"李四");
  Thread thread3=new Thread(tickets,"王五");
  thread.start();
  thread2.start();
  thread3.start();
  
}
}



package lianxi;
import java.util.concurrent.SynchronousQueue;
public class Ticket implements Runnable {
private int number=1000;
@Override
  public void run() {
   while (true){
    synchronized (this){
     if(number>0){
      System.out.println(Thread.currentThread().getName()+this.getClass()+"正在出售第"+number+"张票");
      number--;
     }else{
      break;
     }
   
   }

  }
}
}


作者: zhangyibiao    时间: 2016-3-30 21:20
这种方式解决了多线程中,元素重复的情况
作者: wuyibo    时间: 2016-3-30 22:06
太赞了,谢谢分享

作者: 星辰shine    时间: 2016-3-30 22:11
写的不错,继续加油哈
作者: phoenix1992    时间: 2016-3-30 22:12
不错嘛,加油!很有用!学习了!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2