💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### 卖票问题 ``` public static void main(String[] args) { Ticker ticker = new Ticker(); Thread t1 = new Thread(ticker, "t1"); Thread t2 = new Thread(ticker, "t2"); Thread t3 = new Thread(ticker, "t3"); t1.start(); t2.start(); t3.start(); } public static class Ticker implements Runnable{ private int total = 100; Object lock = new Object(); @Override public void run() { while (true){ if (total > 0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("tick total is = " + total--); } } } } ``` ### 问题? ``` 当我们使用多个线程访问同一资源的时候,且多个线程中对资源有写的操作,就容易出现线程安全问题 ``` ### 怎么解决? ``` 要解决上述多线程并发访问一个资源的安全性问题:也就是解决重复票与不存在票问题,Java中提供了同步机制 (synchronized)来解决。 ``` ``` 为了保证每个线程都能正常执行原子操作,Java引入了线程同步机制。 那么怎么去使用呢?有三种方式完成同步操作: 1. 同步代码块 2. 同步方法 3. 锁机制 ```