本文主要是介绍同步函数--卖票,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class Ticket2 implements Runnable {private int tick = 100;public void run() { //不能将整个run()方法加锁,因为并不是整个函数都需要同步。while (true) {show();}}public synchronized void show(){if (tick > 0) {try {Thread.sleep(10);} catch (Exception e) {}System.out.println(Thread.currentThread().getName() + "sale: " + tick--);}}
}public class ThisLockDemo {public static void main(String[] args) throws InterruptedException {Ticket2 t = new Ticket2(); // t本身不是线程,没有实现Thread对象Thread t1 = new Thread(t); // 创建线程Thread t2 = new Thread(t);Thread t3 = new Thread(t);Thread t4 = new Thread(t);t1.start();t2.start();t3.start();t4.start();}
}
这篇关于同步函数--卖票的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!