线程同步
线程同步(重点、难点)
并发
并发,在
队列和锁
食堂排队
保证安全性,比如厕所可以上锁doge
锁机制synchronized synchronized
package com.zishi.syn;
//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"小黄").start();
new Thread(buyTicket,"老黄").start();//doge
new Thread(buyTicket,"黄牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
每个线程在自己的工作内存交互,内存控制不当会造成数据不一致