解决线程安全问题-同步代码块和同步技术的原理
解决线程安全问题-同步代码块
当我们使用多个线程访问同一资源的时候,且多个线程中对资源有写的操作,就容易出现线程安全问题。
要解决上述多线程并发访问一个资源的安全性问题:也就是解决重复票与不存在票问题,Java中提供了同步机制(synchronized)来解决。
public class RunnableImpl implements Runnable{ Object obj = new Object(); private int ticket = 100; //设置线程任务:卖票 @Override public void run() { //使用死循环,让卖票操作重复执行while(true){ //先判断票是否存在 while (true){ synchronized (obj){ if(ticket>0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //票存在,卖票ticket-- System.out .println(Thread.currentThread( ).getName()+"-->正在卖第" +ticket+"张票"+ticket--); } } } } }
public static void main(String[] args) { RunnableImpl runnable = new RunnableImpl(); Thread thread = new Thread(runnable); Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread.start(); thread1.start(); thread2.start(); }
同步技术的原理


浙公网安备 33010602011771号