运用 Java 同步方法解决多线程卖票案例的数据污染问题。
运用 Java 同步方法解决多线程卖票案例的数据污染问题。
同步方法代码:
public class MyRunnable implements Runnable {
public static int count = 1;
@Override
public void run() {
while(true){
sell();
}
}
// 同步方法,无需写锁对象
public synchronized void sell() {
if(count <= 5){
System.out.println(Thread.currentThread().getName() + " 卖出第" + count + "个口罩");
count++;
}else{
System.out.println("卖光了");
System.exit(0);
}
}
}
测试代码:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r,"窗口A");
Thread t2 = new Thread(r,"窗口B");
t1.start();
t2.start();
}
}
运行结果如下图:
以上案例使用同步方法解决多线程卖票产生的数据污染问题。