java吧 关注:1,270,822贴子:12,777,292
  • 4回复贴,共1

来个大神请教一下多线程啊、、、

只看楼主收藏回复

public class ThreadSellticketDemo {
public static void main(String[] args) {
MyRunnable m1 = new MyRunnable();
Thread t1 = new Thread(m1,"窗口1");
Thread t2 = new Thread(m1,"窗口2");
Thread t3 = new Thread(m1,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable{
private int tickets=100;
private Object obj = new Object();
public void run() {
while(true){
if(tickets==0){
throw new RuntimeException("没有电影票了");
}
synchronized(obj){
if(tickets>0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖"+
(tickets--)+"张电影票");
}
}
}
}
}


1楼2015-06-10 19:36回复
    我能不能把锁加在public void run(){}这里,变成public synchronized void run(){}


    2楼2015-06-10 19:37
    回复
      2025-07-24 10:11:09
      广告
      不感兴趣
      开通SVIP免广告
      不明白方法同步锁还有静态方法同步锁、、、


      3楼2015-06-10 19:37
      回复


        4楼2015-06-10 19:37
        回复


          5楼2015-06-10 19:40
          回复