大致分成:
1.原子更新基本类型
2.原子更新数组
3.原子更新抽象类型
4.原子更新字段
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReference; public class Sequence { private AtomicInteger value=new AtomicInteger(0); private int [] s={2,1,4,6}; AtomicIntegerArray array=new AtomicIntegerArray(s); AtomicReference<User> use=new AtomicReference<>(); AtomicIntegerFieldUpdater<User> old= AtomicIntegerFieldUpdater.newUpdater(User.class, "old"); public int getNext(){ User user=new User(); System.out.println(old.getAndIncrement(user)); System.out.println(old.getAndIncrement(user)); System.out.println(old.getAndIncrement(user)); old.getAndIncrement(user); array.getAndIncrement(2); array.getAndAdd(2, 10); return value.getAndIncrement();//自增value++ //value.incrementAndGet();//++value } public static void main(String[] args) { Sequence s=new Sequence(); new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"" +s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); // new Thread(new Runnable() { // // @Override // public void run() { // System.out.println(Thread.currentThread().getName()+"" // +s.getNext()); // try { // Thread.sleep(100); // } catch (InterruptedException e) { // // e.printStackTrace(); // } // } // // }).start(); } }
Lock接口:
Lock需要显示的获取和释放锁,繁琐,但是能让代码更灵活,随时,获取和释放锁
Synchronized:不需要显示的获取和释放锁 ,简单
使用lock可以方便的实现公平性
非阻塞的获取锁
能被中断的获取锁
超时获取锁
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Sequence { private int value; Lock lock=new ReentrantLock();//所有的线程公用一把锁 public int getNext() { lock.lock(); int a= value++; lock.unlock(); return a; } public static void main(String[] args) { Sequence s = new Sequence(); new Thread(new Runnable() { @Override public void run() { while (true) { System.out.println(Thread.currentThread().getName() + "" + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { System.out.println(Thread.currentThread().getName() + "" + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { System.out.println(Thread.currentThread().getName() + "" + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
原文地址:https://www.cnblogs.com/sunliyuan/p/11143600.html
时间: 2024-11-06 07:34:02