/** * 方式一:同步代码块 * synchronized(同步监视器){ * //需要被同步的代码 * * } * 说明:1.操作共享数据的代码,即为需要被同步的代码,如对总票数的减减、判断是否大于0等操作 * 2.共享数据:多个线程共同操作的变量,如总票数 * 3.同步监视器:俗称“锁”,任何一个类的对象都可以充当锁 * 要求:多个线程必须要共用同一把锁 * */ public class ThreadImplementsDemo { public static void main(String[] args) { ThreadImp threadImp = new ThreadImp(); Thread window1 = new Thread(threadImp); Thread window2 = new Thread(threadImp); Thread window3 = new Thread(threadImp); window1.setName("窗口1"); window2.setName("窗口2"); window3.setName("窗口3"); window1.start(); window2.start(); window3.start(); } } class ThreadImp implements Runnable { //总票数 private int ticket = 100; Object object = new Object(); @Override public void run(){ while(true) { synchronized (object) { if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket); ticket--; } else { break; } } } } }
标签:threadImp,Thread,start,安全,同步,new,中线,多线程,ticket From: https://www.cnblogs.com/sjzchf/p/17070970.html