【解决线程安全问题:同步方法】
同步方法:就是把同步关键字加到方法上
同步方法的锁对象是什么呢?this(不信可以试试把下面的this换成其它对象)
package com.test; public class SellTicket implements Runnable { /**注意,如果是用继承的方式,此处必须用静态修饰*/ private int tickets = 60; private int x = 0; @Override public void run(){ while(true){ if(x%2==0){ synchronized(this){ doSell(); } }else{ sellTicket(); } x++; } } private synchronized void sellTicket() { doSell(); } private void doSell() { if(tickets>0){ try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票"); tickets--; } } }
package com.test; public class SellTicketTest { public static void main(String[] args){ SellTicket sellTicket = new SellTicket(); Thread t1 = new Thread(sellTicket,"窗口一"); Thread t2 = new Thread(sellTicket,"窗口二"); Thread t3 = new Thread(sellTicket,"窗口三"); t1.start(); t2.start(); t3.start(); } }
如果是同步静态方法,那么锁对象就不是this了,而是类的class文件。
终身学习者