在多线程编程中,若干个线程为了可以实现公共资源的操作,通常是复制相应的变量的副本,等操作完成后再将副本与原始变量进行同步处理。但是这样运行速度会稍慢一些,为了提升运行速度,我们可以使用volatile关键字。
普通变量使用流程:
但是使用volatile关键字不能达到线程同步的作用,因此还需写synchronized关键字。
class Sell implements Runnable {
private volatile int ticket = 5;
@Override
public synchronized void run() {
while (this.ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
System.out.println(Thread.currentThread().getName() + "卖出了第" + (5 - --this.ticket) + "张票");
}
}
}
public class JavaDome {
public static void main(String[] args) {
Sell sell = new Sell();
Thread thread1 = new Thread(sell,"窗口一");
Thread thread2 = new Thread(sell,"窗口二");
Thread thread3 = new Thread(sell,"窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}