package com; /** * @author 冀帅 * @date 2020/8/1-15:04 * 使用同步方法解决实现Runnable接口的方式 */ class MyWindow implements Runnable{ private int taciktes = 100; @Override public void run() { while (true){ show(); } } private synchronized void show(){//同步监视器(锁):this if (taciktes>0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+"卖票"+taciktes); taciktes--; } } } public class WindowTest3 { public static void main(String[] args) { MyWindow m = new MyWindow(); Thread t1 = new Thread(m); t1.setName("窗口X"); Thread t2 = new Thread(m); t2.setName("窗口Y"); Thread t3 = new Thread(m); t3.setName("窗口Z"); t1.start(); t2.start(); t3.start(); } }