java多线程的卖票问题

Python032

java多线程的卖票问题,第1张

首先,定义的锁(lock)不对,必须是同一个锁,像你这样用this,new多少个MyThread就有多少个锁,违反了线程的同步机制;

其次,你如果想要呈现多线程的竞争,不可以在run方法里让一个线程一直运行而不释放锁,应该使用wait()/notify();

以下我稍微修改下,会形成两个线程交替执行的情形:

public class ThreadTest {

public static Object obj = new Object()

public static int number = 10// 用static共享票源,不知道可以不,按理说是可以的

/**

 * @param args

 */

public static void main(String[] args) {

// TODO Auto-generated method stub

MyThread my = new MyThread()

MyThread my2 = new MyThread()

Thread t1 = new Thread(my2, "2号窗口")

Thread t2 = new Thread(my, "1号窗口")

t1.start()

t2.start()

}

static class MyThread implements Runnable {

public void run() {

while (true)

synchronized (obj) {

if (number > 0) {

System.out.println(Thread.currentThread().getName()

+ "正在卖票," + "还剩" + number + "张票")

number--

obj.notifyAll()

try {

obj.wait()

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

} else

break

}

}

}

}

很简单, 出票里加锁就行了完整代码:

public class Test {

public static void main(String[] args) {

for(int i=0 i<3 i++){

new Thread("线程 " + i){

public void run() {

while(true){

int p = getNumber()

if(p >0 ){

System.out.println(getName() + " 票号: " + p)

}else{

System.out.println("没票了")

break

}

}

}

}.start()

}

}

public static int num = 100 //总票数

/**

 * synchronized 同步锁

 * @return

 */

public static synchronized int getNumber(){

if(num >0){

return num -- //如果大于0, 则返回当前票并减少一张

}

return 0

}

}