目录
简单的多线程售票代码
Tickets类
public class Tickets { private int num; public Tickets(){} public Tickets(int num){ this.num = num; } public void setNum(int num){ this.num = num; } public int getNum(){ return this.num; } }
SaleTickets类
public class SaleTickets implements SaleInterface{ private Tickets tickets; public SaleTickets(){} public SaleTickets(Tickets tickets){ this.tickets = tickets; } @Override public void sale(){ synchronized (this){ int num = tickets.getNum(); if(tickets.getNum() > 0){ System.out.println(Thread.currentThread().getName() + " 正在售卖第 " + tickets.getNum() + " 张,还剩 " + (tickets.getNum() - 1) + " 张 "); num--; tickets.setNum(num); } } } }
SaleInterfance接口
public interface SaleInterface { public void sale(); }
Test类
public class Test { public static void main(String[] args) { Tickets t = new Tickets(100); SaleTickets st = new SaleTickets(t); new Thread(() -> { while(t.getNum() > 0){ st.sale(); } },"窗口一").start(); new Thread(() -> { while(t.getNum() > 0){ st.sale(); } },"窗口二").start(); } }
我们可以从Test类中看到sale方法都被st这个对象所调用,而线程安全指的是,在堆内存中的数据由于可以被任何线程访问到,在没有限制的情况下存在被意外修改的风险。即堆内存空间在没有保护机制的情况下,对多线程来说是不安全的地方,因为你放进去的数据,可能被别的线程“破坏”。