同步方法和同步代码块()-其他
同步方法和同步代码块()
package edu.wtbu;//不安全的买票public class Demo08 { public static void main(String[] args) { buyTicket buyTicket = new buyTicket(); new Thread(buyTicket,"我").start(); new Thread(buyTicket,"你").start(); new Thread(buyTicket,"黄牛党").start(); }}class buyTicket implements Runnable{ private int ticketNums=10;//票 boolean flag=true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { //模拟延时 Thread.sleep(1000); buy(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } //synchronized 同步方法,锁的是this public synchronized void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag=false; return; } //买票 System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--); }}/*synchronized代码块synchronized(obj){ */
————————
package edu.wtbu;//不安全的买票public class Demo08 { public static void main(String[] args) { buyTicket buyTicket = new buyTicket(); new Thread(buyTicket,"我").start(); new Thread(buyTicket,"你").start(); new Thread(buyTicket,"黄牛党").start(); }}class buyTicket implements Runnable{ private int ticketNums=10;//票 boolean flag=true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { //模拟延时 Thread.sleep(1000); buy(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } //synchronized 同步方法,锁的是this public synchronized void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag=false; return; } //买票 System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--); }}/*synchronized代码块synchronized(obj){ */