java 多线程交替执行
今天我们来聊点多线程的内容。先举个例子,假如有两个售票窗口,但是只有10张票,只能卖给10个人,不能超卖,且要求,1窗口卖一张,2窗口卖下一张,交替售票,这个场景咋玩下。以下是自己的一些思路,请各位大神说说看法
package com.example.feignclient.process;
public class Test1 extends Thread {
private Test test;
public Test1(Test test) {
this.test = test;
}
@Override
public void run() {
while (test.ticket > 0) {
synchronized (test) {
try {
if (test.ticket > 0) {
test.ticket = test.ticket - 1;
System.out.println(Thread.currentThread().getName() + "车票:" + test.ticket);
}
test.notify();
test.wait();
} catch (Exception e) {
e.printStackTrace();
}
if (test.ticket == 0) {
test.notifyAll();
}
}
}
}
}
package com.example.feignclient.process;
public class Test2 extends Thread {
private Test test;
public Test2(Test test) {
this.test = test;
}
@Override
public void run() {
while (test.ticket > 0) {
synchronized (test) {
try {
if (test.ticket > 0) {
test.ticket = test.ticket - 1;
System.out.println(Thread.currentThread().getName() + "车票:" + test.ticket);
}
test.notify();
test.wait();
} catch (Exception e) {
e.printStackTrace();
}
if (test.ticket == 0) {
test.notifyAll();
}
}
}
}
}
package com.example.feignclient.process;
public class Test {
public int ticket = 10;
public static void main(String[] args)throws Exception {
Test test = new Test();
Test1 t1 = new Test1(test);
Test2 t2 = new Test2(test);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(test.ticket);
}
}