《Java编程思想》学习笔记19——并发编程(二)

1.java中的原子操作类:

原子操作是指程序编译后对应于一条CPU操作指令,即原子操作是最小的不可再分指令集,编程中的原子操作是线程安全的,不需要使用进行线程同步和加锁机制来确保原子操作的线程同步。

JDK5中引入了java.util.concurrent.atomic原子操作类包,提供了常用的原子类型操作数据类型,如:AtomicInteger,AtomicLong, AtomicReference等等,原子操作类例子如下:

[java]  view plain copy
  1. import java.util.concurrent.*;  
  2. import java.util.concurrent.atomic.*;  
  3. import java.util.*;  
  4.   
  5. public class AtomicIntegerTest implement Runnable{  
  6.     //创建一个值为0的Integer类型原子类  
  7.     private AtomicInteger i = new AtomicInteger(0);  
  8.     public int getValue(){  
  9.         //获取Integer类型原子类的值  
  10.         return i.get();  
  11. }  
  12. private void evenIncrement(){  
  13.     //值增加2  
  14.     i.addAndGet(2);  
  15. }  
  16. public void run(){  
  17.     while(true){  
  18.     evenIncrement();  
  19. }  
  20. }  
  21. public static void main(String[] args){  
  22.     //创建一个定时任务,5秒钟终止运行  
  23. new Timer().schedule(new TimerTask(){  
  24.     public void run(){  
  25.     System.err.println(“Aborting”);  
  26.     System.exit(0);  
  27. }  
  28. }, 5000);  
  29. ExecutorService exec = Executors.newCachedThreadPool();  
  30. AtomicIntegerTest at = new AtomicIntegerTest();  
  31. Exec.execute(at);  
  32. while(true){  
  33.     int val = at.getValue();  
  34.     //奇数  
  35.     if(val % 2 != 0){  
  36.     System.out.println(val);  
  37.     System.exit(0);  
  38. }  
  39. }  
  40. }  
  41. }  

Java中加减运算等不是原子操作,为了确保线程安全必须确保线程同步安全,使用整数类型的原子类之后,整数原子类的加减运算是原子操作,因此evenIncrement()方法不再需要synchronized关键字或者线程锁机制来确保线程安全。

注意:原子类不是Integer等通用类的通用替换方法,原子类不顶用诸如hashCode和compareTo之类的方法,因为源自变量是可变的,所以不是hash表键的好的选择。

2.线程局部变量:

防止多个线程对同一个共享的资源操作碰撞的另一种方法是使用线程局部变量,线程局部变量的机制是为共享的变量在每个线程中创建一个存储区存储变量副本。线程局部变量ThreadLocal实例通常是类中的private static字段,它们希望将状态与某一个线程相关联。例子如下:

[java]  view plain copy
  1. import java.util.concurrent.atomic.AtomicInteger;  
  2.   
  3. public class UniqueThreadGenerator{  
  4.     private static final AtomicInteger uniqueId = new AtomicInteger(0);  
  5.     //创建一个线程局部变量  
  6.     private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer>(){  
  7.     //覆盖线程局部变量的initialValue方法,为线程局部变量初始化赋值  
  8.     protected Integer initialValue(){  
  9. return uniqueId.getAndIncrement();  
  10. }     
  11. }  
  12. public static int getCurrentThreadId(){  
  13.     //获取线程局部变量的当前线程副本中的值  
  14.     return uniqueId.get();  
  15. }  
  16. }  

线程局部变量java.lang.ThreadLocal类有下面四个方法:

(1).T get():返回此线程局部变量的当前线程副本中的值。

(2).protected T initialValue():返回此线程局部变量的当前线程的初始值。

(3).void remove():移除此线程局部变量当前线程的值。

(4).void set(T value):将此线程局部变量的当前线程副本中的值设置为指定值。

只要线程是活动的并且线程局部变量实例是可访问的,每个线程都保持对其线程局部变量副本的隐式引用。在线程消失之后,其线程局部变量实例的所有副本都会被垃圾回收。

3.线程的yield,sleep和wait的区别:

(1).yield:

正在运行的线程让出CPU时间片,让线程调度器运行其他优先级相同的线程。使用yield()处于可运行状态的线程有可能立刻又进入执行状态。

yield不释放对象锁,即yield线程对象中其他synchronized的数据不能被别的线程使用。

(2).sleep:

当前正在运行的线程进入阻塞状态,sleep是线程Thread类的方法,在sleep的时间内线程肯定不会再运行,sleep可使优先级低得线程得到执行的机会,也可以让同优先级和高优先级的线程有执行机会。

sleep的线程如果持有对象的线程锁,则sleep期间也不会释放线程锁,即sleep线程对象中其他synchronized的数据不能被别的线程使用。

sleep方法可以在非synchronized线程同步的方法中调用,因为sleep()不释放锁。

(3).wait:

正在运行的线程进入等待队列中,wait是Object的方法,线程调用wait方法后会释放掉所持有的对象锁,即wait线程对象中其他synchronized的数据可以被别的线程使用。

wait(), notify()和notifyAll()方法必须只能在synchronized线程同步方法中调用,因为在调用这些方法之前必须首先获得线程锁,如果在非线程同步的方法中调用时,编译时没有问题,但在运行时会抛IllegalMonitorStateException异常,异常信息是当前线程不是方法对象的监视器对象所有者。

4.线程间的通信:

Java中通过wait(),notify()和notifyAll()方法进行线程间的通信,在JDK5之后,又引入了signal()和signalAll()进行线程通信。

(1).wait()和notify(),notifyAll():

wait使得一个正在执行的线程进入阻塞状态,wait也可以象sleep一样指定时间,但是常用的是无参数的wait()方法。notify和notifyAll唤醒处于阻塞态的线程进入可运行状态,通知他们当前的CPU可用。这三个方法都是Object中的方法,不是线程Thread的特有方法。例子如下:

[java]  view plain copy
  1. import java.util.concurent.*;  
  2.   
  3. class Car{  
  4.     private Boolean waxOn = false;  
  5.     public synchronized void waxed(){  
  6.     waxOn = true;  
  7.     notifyAll();  
  8. }  
  9. public synchronized void buffed(){  
  10.     waxOn = false;  
  11.     notifyAll();  
  12. }   
  13. public synchronized void waitForWaxing()throws InterruptedException{  
  14.     while(waxOn == false){  
  15.         wait();  
  16. }  
  17. }  
  18. public synchronized void waitForBuffing()throws InterruptedException{  
  19.     while(waxOn == true){  
  20.     wait();  
  21. }  
  22. }  
  23. }  
  24. class WaxOn implements Runnable{  
  25.     private Car car;  
  26.     public WaxOn(Car c){  
  27.     car = c;  
  28. }  
  29. public void run(){  
  30.     try{  
  31.     while(!Thread.interrupted()){  
  32.     System.out.println(“Wax On!”);  
  33.     TimeUnit.SECONDS.sleep(1);  
  34.     car.waxed();  
  35.     car.waitForBuffing();  
  36. }  
  37. }catch(InterruptedException e){  
  38.     System.out.println(“Exiting via interrupt”);  
  39. }  
  40. System.out.println(“Ending Wax On task”);  
  41. }  
  42. }  
  43. class WaxOff implements Runnable{  
  44.     private Car car;  
  45.     public WaxOff(Car c){  
  46.     car = c;  
  47. }  
  48. public void run(){  
  49.     try{  
  50.     while(!Thread.interrupted()){  
  51.         car.waitForWaxing();  
  52.     System.out.println(“Wax Off!”);  
  53.     TimeUnit.SECONDS.sleep(1);  
  54.     car.buffed();  
  55. }  
  56. }catch(InterruptedException e){  
  57.     System.out.println(“Exiting via interrupt”);  
  58. }  
  59. System.out.println(“Ending Wax Off task”);  
  60. }  
  61. }  
  62. public class WaxOMatic{  
  63.     public static void main(String[] args)throws Exception{  
  64.     Car car = new Car();  
  65.     ExecutorService exec = Executors.newCachedThreadPool();  
  66.     exec.execute(new WaxOff(car));  
  67.     exec.execute(new WaxOn(car));  
  68.     TimeUnit.SECONDS.sleep(5);  
  69.     exec.shutdownNow();  
  70. }  
  71. }  

输出结果:

Wax On! Wax Off! Wax On! Wax Off! Wax On!

Exiting via interrupt

Ending Wax On task

Exiting via interrupt

Ending Wax Off task

注意:waite (),notify()和notifyAll()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运行时会发生IllegalMonitorStateException的异常。

(2).await(), signal()和signalAll()进行线程通信:

JDK5中引入了线程锁Lock来实现线程同步,使用Condition将对象的监视器分解成截然不同的对象,以便通过这些对象与任意线程锁Lock组合使用,使用signal和signalAll唤醒处于阻塞状态的线程,例子如下:

[java]  view plain copy
  1. import java.util.concurrent.*;  
  2. import java.util.concurrent.lock.*;  
  3.   
  4. class Car{  
  5.     private Lock lock = new ReentrantLock();  
  6.     //获取线程锁的条件实例  
  7.     private Condition condition = lock.newCondition();  
  8.     private Boolean waxOn = false;  
  9.     public void waxed(){  
  10.     lock.lock();  
  11.     try{  
  12.     waxOn = true;  
  13.     //唤醒等待的线程  
  14.     condition.signalAll();  
  15. }finally{  
  16.     lock.unlock();  
  17. }  
  18. }  
  19. public void buffed(){  
  20.     lock.lock();  
  21.     try{  
  22.     waxOn = false;  
  23.     //唤醒等待的线程  
  24.     condition.signalAll();  
  25. }finally{  
  26.     lock.unlock();  
  27. }  
  28. }   
  29. public void waitForWaxing()throws InterruptedException{  
  30.     lock.lock();  
  31.     try{  
  32.     while(waxOn == false){  
  33.         //使当前线程处于等待状态  
  34.     condition.await();  
  35. }finally{  
  36.     lock.unlock();  
  37. }  
  38. }  
  39. }  
  40. public void waitForBuffing()throws InterruptedException{  
  41.     lock.lock();  
  42.     try{  
  43.     while(waxOn == true){  
  44.         //使当前线程处于等待状态  
  45.     condition.await();  
  46. }finally{  
  47.     lock.unlock();  
  48. }  
  49. }  
  50. }  
  51. }  
  52. class WaxOn implements Runnable{  
  53.     private Car car;  
  54.     public WaxOn(Car c){  
  55.     car = c;  
  56. }  
  57. public void run(){  
  58.     try{  
  59.     while(!Thread.interrupted()){  
  60.     System.out.println(“Wax On!”);  
  61.     TimeUnit.SECONDS.sleep(1);  
  62.     car.waxed();  
  63.     car.waitForBuffing();  
  64. }  
  65. }catch(InterruptedException e){  
  66.     System.out.println(“Exiting via interrupt”);  
  67. }  
  68. System.out.println(“Ending Wax On task”);  
  69. }  
  70. }  
  71. class WaxOff implements Runnable{  
  72.     private Car car;  
  73.     public WaxOff(Car c){  
  74.     car = c;  
  75. }  
  76. public void run(){  
  77.     try{  
  78.     while(!Thread.interrupted()){  
  79.         car.waitForWaxing();  
  80.     System.out.println(“Wax Off!”);  
  81.     TimeUnit.SECONDS.sleep(1);  
  82.     car.buffed();  
  83. }  
  84. }catch(InterruptedException e){  
  85.     System.out.println(“Exiting via interrupt”);  
  86. }  
  87. System.out.println(“Ending Wax Off task”);  
  88. }  
  89. }  
  90. public class WaxOMatic{  
  91.     public static void main(String[] args)throws Exception{  
  92.     Car car = new Car();  
  93.     ExecutorService exec = Executors.newCachedThreadPool();  
  94.     exec.execute(new WaxOff(car));  
  95.     exec.execute(new WaxOn(car));  
  96.     TimeUnit.SECONDS.sleep(5);  
  97.     exec.shutdownNow();  
  98. }  
  99. }  

输出结果:

Wax On! Wax Off! Wax On! Wax Off! Wax On!

Exiting via interrupt

Ending Wax On task

Exiting via interrupt

Ending Wax Off task

5.使用ScheduledThreadPoolExecutor实现定时任务:

JDK1.5之前,使用Timer实现定时任务,JDK1.5之后引入了ScheduleThreadPoolExecutor实现多线程的定时任务。例子如下:

[java]  view plain copy
  1. import java.util.concurrent.*;  
  2. import java.util.*;  
  3.   
  4. public class DemoSchedule{  
  5.     private final ScheduledExecutorService scheduler =   
  6.  Executors.newScheduledThreadPool(1);  
  7.     //创建并在给定延迟后时间启动的一次性操作  
  8. public void schedule(Runnable event, long delay){  
  9.     scheduler.schedule(event, delay, TimeUnit.SECOND);  
  10. }  
  11. //创建并在给定延迟时间之后,每个给定时间周期性执行的操作  
  12.     public void repeat(Runnable event, long initialDelay, long period){  
  13.     scheduler.scheduleAtFixedRate(event, initialDelay, period, TimeUnit.SECOND);  
  14. }  
  15. }  
  16. class OnetimeSchedule implement Runnable{  
  17.     public void run(){  
  18.     System.out.println(“One time schedule task”);  
  19. }  
  20. }   
  21. class RepeatSchedule implement Runnable{  
  22.     public void run(){  
  23.     System.out.println(“Repeat schedule task”);  
  24. }  
  25. }  
  26. class TestSchedule {  
  27.     public static void main(String[] args){  
  28.     DemoSchedule scheduler = new DemoSchedule();  
  29.     scheduler.schedule(new OnetimeSchedule(), 5);  
  30.     scheduler.schedule(new RepeatSchedule (), 1010);  
  31. }  
  32. }  

输出结果:

5秒钟之后打印输出:One timeschedule task

10秒钟之后打印输出:Repeatschedule task

之后每隔10秒钟打印输出:Repeat schedule task

6.信号量Semaphore:

一个正常的线程同步锁concurrent.locks或者内置的synchronized只允许同一时间一个任务访问一个资源,而计数信号量Semaphore运行多个任务在同一时间访问一个资源。Semaphore是一个计数信号量,维护了一个许可集,通常用于限制可以访问某些资源的线程数目。例子如下:

[java]  view plain copy
  1. import java.util.concurrent.*;  
  2. import java.util.*;  
  3.   
  4. public class Pool<T> {  
  5.     //限制的线程数目  
  6.     private int size;  
  7.     //存放资源集合  
  8.     private List<T> items = new ArrayList<T>();  
  9.     //标记资源是否被使用  
  10.     private volatile boolean[] checkedOut;  
  11.     private Semaphore available;  
  12.     public Pool(Class<T> classObject, int size){  
  13.     this.size = size;  
  14.     checkedOut = new boolean[size];  
  15.     //创建信号量对象  
  16.     available = new Semaphore(size, true);  
  17.     for(int i = 0; i < size; ++i){  
  18.     try{  
  19.         //加载资源对象并存放到集合中  
  20.     items.add(classObject.newInstance());  
  21. }catch(Exception e){  
  22. throw new RuntimeException(e);  
  23. }  
  24. }  
  25. }  
  26. //访问资源  
  27. public T checkout() throws InterruptedException{  
  28.     //从信号量中获取一个资源许可  
  29.     available.acquired();  
  30.     return getItem();  
  31. }  
  32. //释放资源  
  33. public void checkIn(T x){  
  34.     if(releaseItem(x))  
  35.         //释放一个资源许可,将其返回给信号量  
  36.         available.release();  
  37. }  
  38. //获取资源  
  39. private synchronized T getItem(){  
  40.     for(int i = 0; i < size; ++i){  
  41.         //资源没有被使用  
  42.     if(!checkedOut[i]){  
  43.         //标记资源被使用  
  44.     checkedOut[i] = true;  
  45.     return items.get(i);  
  46. }  
  47. }  
  48. return null;  
  49. }  
  50. private synchronized boolean releaseItem(T item){  
  51.     int index = items.indexOf(item);  
  52.     //资源不在资源集合中  
  53.     if(index == -1return false;  
  54.     //资源正在被使用  
  55.     if(checkedOut[index]){  
  56.         //将资源标记为不再使用  
  57.     checkedOut[index] = false;  
  58.     return true;  
  59. }  
  60. return false;  
  61. }  
  62. }  

在访问资源前,每个线程必须首先从信号量获取许可,从而保证可以使用该资源。该线程结束后,将资源释放回资源池中并将许可返回给信号量,从而允许其他线程获取和使用该资源。

如果当前信号量中没有资源访问许可,则信号量会阻塞调用的线程直到获取一个资源许可,否则,线程将被中断。

注意:调用信号量的acquire时无法保持同步锁,因为这会阻止将该资源返回到资源池中,信号量封装所需要的同步,以限制对资源池的访问。

7.Exchanger线程同步交换器:

Exchanger类,可以用来完成线程间的数据交换。 类java.util.concurrent.Exchanger提供了一个同步点,在这个同步点,一对线程可以交换数据。每个线程通过exchange()方法的入口提供数据给他的伙伴线程,并接收他的伙伴线程提供的数据,并返回。当两个线程通过Exchanger交换了对象,这个交换对于两个线程来说都是安全的。例子如下:

[java]  view plain copy
  1. //杯子类  
  2. class Cup{  
  3. private int capacity = 0;  
  4. public Cup(int capacity){  
  5. this.capacity = capacity;  
  6. }  
  7. public int getCapacity(){  
  8.     return capacity;  
  9. }  
  10. public void addWaterToCup(int i){  
  11. capacity += I;  
  12.         capacity = capacity > 100 ? 100 : capacity;  
  13. }  
  14. public void drinkWaterFromCup(int i){  
  15. capacity += I;  
  16. capacity = capacity < 0 ? 0 : capacity;  
  17. }  
  18. public void isFull(){  
  19. return capacity == 100 ? true : false;  
  20. }  
  21. public void isEmpty(){  
  22. return capacity == 0 ? true : false;  
  23. }  
  24. }  
  25. import  java.util.concurrent.Exchanger;  
  26. import java.util.*;  
  27.   
  28. public class TestExchanger{  
  29.     Cup emptyCup = new Cup(0);  
  30.     Cup fullCup = new Cup(100);  
  31.     Exchanger<Cup> exchanger = new Exchanger<Cup>();  
  32.       
  33. //服务员类  
  34. class Waiter implements Runnable{  
  35.         private int addSpeed = 1;  
  36.         public Waiter(int addSpeed){  
  37.         this.addSpeed = addSpeed;  
  38. }  
  39. public void run(){  
  40.         while(emptyCup != null){  
  41.         try{  
  42.             //如果杯子已满,则与顾客交换,服务员有获得空杯子  
  43.         if(emptyCup.isFull()){  
  44.         emptyCup = exchanger.exchange(emptyCup);  
  45.         System.out.println(“Waiter: ” + emptyCup. getCapacity());  
  46. }else{  
  47.     emptyCup.addWaterToCup(addSpeed);  
  48. System.out.println(“Waiter add ” + addSpeed +   
  49. “ and current capacity is:” + emptyCup. getCapacity());  
  50.                         TimeUnit.SECONDS.sleep(new Random().nextInt(10));  
  51. }  
  52. }catch(InterruptedException e){  
  53.     e.printStackTrack();  
  54. }  
  55. }  
  56. }  
  57. }  
  58. //顾客类  
  59. class Customer implements Runnable{  
  60.     int drinkSpeed = 1;  
  61.     public Customer(int drinkSpeed){  
  62.     this.drinkSpeed = drinkSpeed;  
  63. }  
  64. public void run(){  
  65.     while(fullCup != null){  
  66.     try{  
  67.         //如果杯子已空,则与服务员进行交换,顾客获得装满水的杯子  
  68.         if(fullCup.isEmpty()){  
  69.     fullCup = exchanger.exchanger(fullCup);  
  70. System.out.println(“Customer: ” + fullCup. getCapacity());  
  71. }else{  
  72.     fullCup.drinkWaterFromCup(drinkSpeed);  
  73. System.out.println(“Customer drink ” + drinkSpeed +   
  74. “ and current capacity is:” + fullCup.getCapacity());  
  75.                         TimeUnit.SECONDS.sleep(new Random().nextInt(10));  
  76. }  
  77. }catch(InterruptedException e){  
  78.     e.printStackTrack();  
  79. }  
  80. }  
  81. }  
  82. }  
  83. public static void main(String[] args){  
  84.     new Thread(new Waiter(3)).start();  
  85.     new Thread(new Customer(6)).start();  
  86. }  
  87. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值