我们创建4个线程,与之前不同的是,同时使用了同步函数和同步代码快。看看结果如何
class Mlpc implements Runnable { private int ticket = 550; public boolean flag = true; Object obj = new Object(); public void run() { if(flag == true) { while(true) { synchronized (obj) { if(ticket>0) { if(ticket>0) { try { Thread.sleep(20); } catch (Exception e) { } System.out.println(Thread.currentThread()+" show "+ticket--); } } } } } else { while(true) { show(); } } } public synchronized void show() { if(ticket>0) { try { Thread.sleep(20); } catch (Exception e) { } System.out.println(Thread.currentThread()+" show "+ticket--); } } } class mlpcDemo { public static void main(String[] args) { Mlpc m = new Mlpc(); Thread th0 = new Thread(m); Thread th1 = new Thread(m); Thread th2 = new Thread(m); Thread th3 = new Thread(m); th0.start(); try { Thread.sleep(20); } catch (Exception e) { } m.flag = false; th1.start(); th2.start(); th3.start(); } }
结果出现了票数为0。
public void run() { if(flag == true) { while(true) { synchronized (this) //从原本的任意对象改为函数自己所属的对象this { if(ticket>0) { try { Thread.sleep(20); } catch (Exception e) { } System.out.println(Thread.currentThread()+" show "+ticket--); } } } } else { while(true) { show(); } } }
时间: 2024-09-29 17:11:02