基本概念
什么是线程安全问题
当多个线程同时共享 一个全局变量做写的操作时候,可能会收到其他线程的干扰,就会产生线程安全问题,导致数据脏读。
模拟有线程安全问题的代码
public class TicketThread implements Runnable {
private int count = 100;
@Override
public void run() {
while (count > 0) {
try {
Thread.sleep(30);
} catch (Exception e) {
}
ticket();
}
}
private void ticket() {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
}
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
Thread thread1 = new Thread(ticketThread, "窗口1");
Thread thread2 = new Thread(ticketThread, "窗口2");
thread1.start();
thread2.start();
}
}
标签:count,Thread,TicketThread,线程,ticketThread,new,asdf
From: https://www.cnblogs.com/YeQuShangHun/p/16591042.html