java多執行緒快速入門(十一)
阿新 • • 發佈:2018-11-25
在方法上面加synchonizd用的是this鎖
package com.cppdy; class MyThread7 implements Runnable { private Integer ticketCount = 100; public boolean falg = true; @Override public void run() { if (falg) { synchronized (this) { while (ticketCount > 0) {try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "賣出了第:" + (100 - ticketCount + 1) + "張票。"); ticketCount--; } } } else { while (ticketCount > 0) { sale(); } } } public synchronized void sale() { if (ticketCount > 0) { try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "賣出了第:" + (100 - ticketCount + 1) + "張票。"); ticketCount--; } } } public class ThreadDemo7 { public static void main(String[] args) throws Exception { MyThread7 mt = new MyThread7(); Thread thread1 = new Thread(mt, "視窗1"); Thread thread2 = new Thread(mt, "視窗2"); thread1.start(); Thread.sleep(30); mt.falg = false; thread2.start(); } }