在此基于自动集成器实现。
包donggua Bai.cas; import Java.util.concurrent.atomic.atomic integer;/* * @ authordongguabai * @ description * @ date 2021-02-2118336053 */publicclasscaslock {/* * 0表示未锁定,1表示*/pppp public void lock () while(true ) if ) state.compareandset (0,1 ) ) system.out.println ) thread.curent threared } } } public void unLock () system.out.println ) thread.currentthread ) ).getName ) -解锁); state.set(0; }请测试一下:
包donggua Bai.cas;/* * @ authordongguabai * @ description * @ date 2021-02-2118336056 */public class main { publicstaticvoidmain (stion new try { lock.lock (; }finally { lock.unLock (); () ).start ); new Thread ()-{system.out.println ) thread.currentthread ) ).getName ) -尝试锁定) }; try { lock.lock (; }finally { lock.unLock (); () ).start ); }输出结果:
真读-0-锁定真读-0-锁定成功真读-0-解锁真读-1-解锁真读-1-解锁成功