如何保证线程安全
什么是线程安全问题?
在多线程情况下,对共享内存中的变量做写操作时,就会容易出现线程安全问题。
举个栗子,我们现在要用两个线程实现两个窗口售卖5张票
class ThreadSaleTicket extends Thread{
public int ticket = 5;
@Override
public void run() {
while(ticket > 0){
sale();
}
}
public void sale(){
System.out.println(Thread.currentThread().getName() + "售出第: " + (5-ticket+1) + " 张票");
ticket--;
}
}
public class threadSecurityTest{
public static void main(String[] args) {
ThreadSaleTicket salethread1 = new ThreadSaleTicket();
Thread thread1 = new Thread(salethread1,"窗口1");
Thread thread2 = new Thread(salethread1,"窗口2");
thread1.start();
thread2.start