无锁类的使用----AtomicReference

来源:互联网 发布:nba2kol伦纳德2017数据 编辑:程序博客网 时间:2024/06/07 23:22
package suanfa;import java.util.Random;import java.util.concurrent.atomic.AtomicReference;class MyThread extends Thread{private AtomicReference<String> flag;public MyThread(AtomicReference<String> flag,String name){super(name);this.flag = flag;}@Overridepublic void run() {int time = new Random().nextInt(500);try {Thread.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}if(flag.compareAndSet("cx", "gx")){System.out.println(Thread.currentThread().getName()+":success");}else {System.out.println(Thread.currentThread().getName()+":failed");}}}public class NoLock {public static void main(String[] args) throws Exception {AtomicReference<String> flag = new AtomicReference<String>("cx");for(int i=0;i<10;i++){new MyThread(flag,i+"").start();}System.out.println("main:"+flag.get());}}

0 0
原创粉丝点击