多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
#### 同步方法 ``` 同步方法:使用synchronized修饰的方法,就叫做同步方法,保证A线程执行该方法的时候,其他线程只能在方法外等着 ``` ``` public synchronized void method(){     可能会产生线程安全问题的代码   } ``` #### 同步锁是谁? ``` 对于非static方法,同步锁就是this。 对于static方法,我们使用当前方法所在类的字节码对象(类名.class)。 ``` ``` public static class Ticker implements Runnable{ private int total = 100; Object lock = new Object(); @Override public void run() { while (true){ sellTick(); } } //同步方法 private synchronized void sellTick(){ if (total > 0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("tick total is = " + total--); } } } ```