java多線程快速入門(十一)
阿新 • • 發佈:2018-11-25
lee read .get java多線 als pub syn this ble
在方法上面加synchonizd用的是this鎖
package com.cppdy; class MyThread7 implements Runnable { private Integer ticketCount = 100; public boolean falg = true; @Override public void run() { if (falg) { while (ticketCount > 0) { synchronized (this) {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(); } }
java多線程快速入門(十一)