class Mythread implements Runnable{ private int ticket =5; public void run(){ for(int i =0;i<100;i++){ //使用同步代码块解决多线程卖票资源共享的问题 synchronized (this){ if(ticket > 0){ try{ Thread.sleep(300); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("sell ticket = " + ticket--); } } } }}public class ThreadDemo04{ public static void main(String[] args){ Mythread mt = new Mythread(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); t1.start(); t2.start(); t3.start(); }}//同步方法class Mythread implements Runnable{ private int ticket = 5; public void run(){ for(int i=0;i<100;i++){ this.sale(); } } //同步方法 public synchronized void sale(){ if(ticket > 0){ try{ Thread.sleep(300); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("sale ticket = " + ticket--); } }}public class ThreadDemo05{ public static void main(String[] args){ Mythread mt = new Mythread(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); t1.start(); t2.start(); t3.start(); }}