synchronized 同步代码块,售票问题
Posted lijins
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了synchronized 同步代码块,售票问题相关的知识,希望对你有一定的参考价值。
package cn.ljs.FristSync; public class SalerDemo extends Thread { static int tickets = 1000; String name; static Object lock = new Object(); public SalerDemo(String name) { this.name = name; } public void run(){ while(true){ synchronized (lock) { if (tickets < 1) { return ; } System.out.println(name + ": " + tickets); tickets--; } } } public static void main(String[] args) { Thread t1 = new SalerDemo("saler1"); Thread t2 = new SalerDemo("saler2"); Thread t3 = new SalerDemo("saler3"); t1.start(); t2.start(); t3.start(); } }
以上是关于synchronized 同步代码块,售票问题的主要内容,如果未能解决你的问题,请参考以下文章
synchronized (lock) 买票demo 线程安全