package com.LearnJava.Thread; /* 同步代码块 synchronized(同步监视器){ //需要同步的代码 } 同步监视器:俗称 锁,可以是任何实例化的类.但是需要共用同一个实例. */ class WindowSell implements Runnable{ Object obj = new Object(); private int ticket = 100; @Override public void run() { while (true) { synchronized(obj){ if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "sell " + ticket--); }else{ break; } } Thread.yield(); } } } public class ThreadTestTicket { public static void main(String[] args) { WindowSell win = new WindowSell(); Thread t1 = new Thread(win); t1.setName("1号窗口"); Thread t2 = new Thread(win); t2.setName("2号窗口"); Thread t3 = new Thread(win); t3.setName("3号窗口"); t1.start(); t2.start(); t3.start(); } }
原文地址:https://www.cnblogs.com/superxuezhazha/p/12275958.html
时间: 2024-10-14 12:21:27