您的位置:首页 > 编程语言 > Java开发

《Java编程思想第四版》笔记---21章(2) 并发

2016-08-27 00:21 239 查看
1.java中的原子操作类(P684 21.3.4)
原子操作是指程序编译后对应于一条CPU操作指令,即原子操作是最小的不可再分指令集,编程中的原子操作是线程安全的,不需要使用进行线程同步和加锁机制来确保原子操作的线程同步。
JDK5中引入了java.util.concurrent.atomic原子操作类包,提供了常用的原子类型操作数据类型,如:AtomicInteger,AtomicLong, AtomicReference等等,原子操作类例子如下:

import java.util.concurrent.*;

import java.util.concurrent.atomic.*;

import java.util.*;


public class AtomicIntegerTest implement Runnable{

//创建一个值为0的Integer类型原子类

private AtomicInteger i = new AtomicInteger(0);

public int getValue(){

//获取Integer类型原子类的值

return i.get();

}

private void evenIncrement(){

//值增加2

i.addAndGet(2);

}

public void run(){

while(true){

evenIncrement();

}

}

public static void main(String[] args){

//创建一个定时任务,5秒钟终止运行

new Timer().schedule(new TimerTask(){

public void run(){

System.err.println(“Aborting”);

System.exit(0);

}

}, 5000);

ExecutorService exec = Executors.newCachedThreadPool();

AtomicIntegerTest at = new AtomicIntegerTest();

Exec.execute(at);

while(true){

int val = at.getValue();

//奇数

if(val % 2 != 0){

System.out.println(val);

System.exit(0);

}

}

}

}

[/code]

Java中加减运算等不是原子操作,为了确保线程安全必须确保线程同步安全,使用整数类型的原子类之后,整数原子类的加减运算是原子操作,因此evenIncrement()方法不再需要synchronized关键字或者线程锁机制来确保线程安全。
注意:原子类不是Integer等通用类的通用替换方法,原子类不顶用诸如hashCode和compareTo之类的方法,因为源自变量是可变的,所以不是hash表键的好的选择。
2.线程本地存储(P690 21.3.7)
防止多个线程对同一个共享的资源操作碰撞的另一种方法是使用线程局部变量,线程局部变量的机制是为共享的变量在每个线程中创建一个存储区存储变量副本。线程局部变量ThreadLocal实例通常是类中的private static字段,它们希望将状态与某一个线程相关联。例子如下:

import java.util.concurrent.atomic.AtomicInteger;


public class UniqueThreadGenerator{

private static final AtomicInteger uniqueId = new AtomicInteger(0);

//创建一个线程局部变量

private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer>(){

//覆盖线程局部变量的initialValue方法,为线程局部变量初始化赋值

 protected Integer initialValue(){

 return uniqueId.getAndIncrement();

 }

}

public static int getCurrentThreadId(){

//获取线程局部变量的当前线程副本中的值

return uniqueId.get();

}

}

[/code]

线程局部变量java.lang.ThreadLocal类有下面四个方法:
(1) T get():返回此线程局部变量的当前线程副本中的值。
(2) protected T initialValue():返回此线程局部变量的当前线程的初始值。
(3) void remove():移除此线程局部变量当前线程的值。
(4) void set(T value):将此线程局部变量的当前线程副本中的值设置为指定值。
只要线程是活动的并且线程局部变量实例是可访问的,每个线程都保持对其线程局部变量副本的隐式引用。在线程消失之后,其线程局部变量实例的所有副本都会被垃圾回收。
ThreadLocal通常作为静态存储区域,在创建ThreadLocal时,只能使用get()和set()方法访问该对象的内容。
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.线程间的通信(P702)
Java中通过wait(),notify()和notifyAll()方法进行线程间的通信,在JDK5之后,又引入了signal()和signalAll()进行线程通信。
(1).wait()和notify(),notifyAll():
wait使得一个正在执行的线程进入阻塞状态,wait也可以象sleep一样指定时间,但是常用的是无参数的wait()方法。notify和notifyAll唤醒处于阻塞态的线程进入可运行状态,通知他们当前的CPU可用。这三个方法都是Object中的方法,不是线程Thread的特有方法。例子如下:

import java.util.concurent.*;


class Car{

private Boolean waxOn = false;

public synchronized void waxed(){

waxOn = true;

notifyAll();

}

public synchronized void buffed(){

waxOn = false;

notifyAll();

}

public synchronized void waitForWaxing()throws InterruptedException{

while(waxOn == false){

wait();

}

}

public synchronized void waitForBuffing()throws InterruptedException{

while(waxOn == true){

wait();

}

}

}

class WaxOn implements Runnable{

private Car car;

public WaxOn(Car c){

car = c;

}

public void run(){

try{

while(!Thread.interrupted()){

System.out.println(“Wax On!”);

TimeUnit.SECONDS.sleep(1);

car.waxed();

car.waitForBuffing();

}

}catch(InterruptedException e){

System.out.println(“Exiting via interrupt”);

}

System.out.println(“Ending Wax On task”);

}

}

class WaxOff implements Runnable{

private Car car;

public WaxOff(Car c){

car = c;

}

public void run(){

try{

while(!Thread.interrupted()){

car.waitForWaxing();

System.out.println(“Wax Off!”);

TimeUnit.SECONDS.sleep(1);

car.buffed();

}

}catch(InterruptedException e){

System.out.println(“Exiting via interrupt”);

}

System.out.println(“Ending Wax Off task”);

}

}

public class WaxOMatic{

public static void main(String[] args)throws Exception{

Car car = new Car();

ExecutorService exec = Executors.newCachedThreadPool();

exec.execute(new WaxOff(car));

exec.execute(new WaxOn(car));

TimeUnit.SECONDS.sleep(5);

exec.shutdownNow();

}

}

[/code]

输出结果:
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唤醒处于阻塞状态的线程,例子如下:

import java.util.concurrent.*;

import java.util.concurrent.lock.*;


class Car{

private Lock lock = new ReentrantLock();

//获取线程锁的条件实例

private Condition condition = lock.newCondition();

private Boolean waxOn = false;

public void waxed(){

lock.lock();

try{

waxOn = true;

//唤醒等待的线程

condition.signalAll();

}finally{

lock.unlock();

}

}

public void buffed(){

lock.lock();

try{

waxOn = false;

//唤醒等待的线程

condition.signalAll();

}finally{

lock.unlock();

}

}

public void waitForWaxing()throws InterruptedException{

lock.lock();

try{

while(waxOn == false){

//使当前线程处于等待状态

condition.await();

}finally{

lock.unlock();

}

}

}

public void waitForBuffing()throws InterruptedException{

lock.lock();

try{

while(waxOn == true){

//使当前线程处于等待状态

condition.await();

}finally{

lock.unlock();

}

}

}

}

class WaxOn implements Runnable{

private Car car;

public WaxOn(Car c){

car = c;

}

public void run(){

try{

while(!Thread.interrupted()){

System.out.println(“Wax On!”);

TimeUnit.SECONDS.sleep(1);

car.waxed();

car.waitForBuffing();

}

}catch(InterruptedException e){

System.out.println(“Exiting via interrupt”);

}

System.out.println(“Ending Wax On task”);

}

}

class WaxOff implements Runnable{

private Car car;

public WaxOff(Car c){

car = c;

}

public void run(){

try{

while(!Thread.interrupted()){

car.waitForWaxing();

System.out.println(“Wax Off!”);

TimeUnit.SECONDS.sleep(1);

car.buffed();

}

}catch(InterruptedException e){

System.out.println(“Exiting via interrupt”);

}

System.out.println(“Ending Wax Off task”);

}

}

public class WaxOMatic{

public static void main(String[] args)throws Exception{

Car car = new Car();

ExecutorService exec = Executors.newCachedThreadPool();

exec.execute(new WaxOff(car));

exec.execute(new WaxOn(car));

TimeUnit.SECONDS.sleep(5);

exec.shutdownNow();

}

}

[/code]

输出结果:
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实现定时任务(P722)
JDK1.5之前,使用Timer实现定时任务,JDK1.5之后引入了ScheduleThreadPoolExecutor实现多线程的定时任务。例子如下:

import java.util.concurrent.*;

import java.util.*;


public class DemoSchedule{

private final ScheduledExecutorService scheduler = 

 Executors.newScheduledThreadPool(1);

//创建并在给定延迟后时间启动的一次性操作

public void schedule(Runnable event, long delay){

scheduler.schedule(event, delay, TimeUnit.SECOND);

}

//创建并在给定延迟时间之后,每个给定时间周期性执行的操作

public void repeat(Runnable event, long initialDelay, long period){

scheduler.scheduleAtFixedRate(event, initialDelay, period, TimeUnit.SECOND);

}

}

class OnetimeSchedule implement Runnable{

public void run(){

System.out.println(“One time schedule task”);

}

}

class RepeatSchedule implement Runnable{

public void run(){

System.out.println(“Repeat schedule task”);

}

}

class TestSchedule {

public static void main(String[] args){

DemoSchedule scheduler = new DemoSchedule();

scheduler.schedule(new OnetimeSchedule(), 5);

scheduler.schedule(new RepeatSchedule (), 10, 10);

}

}

[/code]

输出结果:
5秒钟之后打印输出:One timeschedule task
10秒钟之后打印输出:Repeatschedule task
之后每隔10秒钟打印输出:Repeat schedule task
6.信号量Semaphore(P733)
一个正常的线程同步锁concurrent.locks或者内置的synchronized只允许同一时间一个任务访问一个资源,而计数信号量Semaphore运行多个任务在同一时间访问一个资源。Semaphore是一个计数信号量,维护了一个许可集,通常用于限制可以访问某些资源的线程数目。例子如下:

import java.util.concurrent.*;

import java.util.*;


public class Pool<T> {

//限制的线程数目

private int size;

//存放资源集合

private List<T> items = new ArrayList<T>();

//标记资源是否被使用

private volatile boolean[] checkedOut;

private Semaphore available;

public Pool(Class<T> classObject, int size){

this.size = size;

checkedOut = new boolean[size];

//创建信号量对象

available = new Semaphore(size, true);

for(int i = 0; i < size; ++i){

try{

//加载资源对象并存放到集合中

items.add(classObject.newInstance());

}catch(Exception e){

throw new RuntimeException(e);

}

}

}

//访问资源

public T checkout() throws InterruptedException{

//从信号量中获取一个资源许可

available.acquired();

return getItem();

}

//释放资源

public void checkIn(T x){

if(releaseItem(x))

//释放一个资源许可,将其返回给信号量

available.release();

}

//获取资源

private synchronized T getItem(){

for(int i = 0; i < size; ++i){

//资源没有被使用

if(!checkedOut[i]){

//标记资源被使用

checkedOut[i] = true;

return items.get(i);

}

}

return null;

}

private synchronized boolean releaseItem(T item){

int index = items.indexOf(item);

//资源不在资源集合中

if(index == -1) return false;

//资源正在被使用

if(checkedOut[index]){

//将资源标记为不再使用

checkedOut[index] = false;

return true;

}

return false;

}

}

[/code]

在访问资源前,每个线程必须首先从信号量获取许可,从而保证可以使用该资源。该线程结束后,将资源释放回资源池中并将许可返回给信号量,从而允许其他线程获取和使用该资源。
如果当前信号量中没有资源访问许可,则信号量会阻塞调用的线程直到获取一个资源许可,否则,线程将被中断。
注意:调用信号量的acquire时无法保持同步锁,因为这会阻止将该资源返回到资源池中,信号量封装所需要的同步,以限制对资源池的访问。
7.Exchanger线程同步交换器(P735)
Exchanger类,可以用来完成线程间的数据交换。 类java.util.concurrent.Exchanger提供了一个同步点,在这个同步点,一对线程可以交换数据。每个线程通过exchange()方法的入口提供数据给他的伙伴线程,并接收他的伙伴线程提供的数据,并返回。当两个线程通过Exchanger交换了对象,这个交换对于两个线程来说都是安全的。例子如下:

//杯子类

class Cup{

private int capacity = 0;

public Cup(int capacity){

this.capacity = capacity;

}

public int getCapacity(){

return capacity;

}

public void addWaterToCup(int i){

capacity += I;

capacity = capacity > 100 ? 100 : capacity;

}

public void drinkWaterFromCup(int i){

capacity += I;

capacity = capacity < 0 ? 0 : capacity;

}

public void isFull(){

return capacity == 100 ? true : false;

}

public void isEmpty(){

return capacity == 0 ? true : false;

}

}

importjava.util.concurrent.Exchanger;

import java.util.*;


public class TestExchanger{

Cup emptyCup = new Cup(0);

Cup fullCup = new Cup(100);

Exchanger<Cup> exchanger = new Exchanger<Cup>();


//服务员类

class Waiter implements Runnable{

private int addSpeed = 1;

public Waiter(int addSpeed){

this.addSpeed = addSpeed;

}

public void run(){

while(emptyCup != null){

try{

//如果杯子已满,则与顾客交换,服务员有获得空杯子

if(emptyCup.isFull()){

emptyCup = exchanger.exchange(emptyCup);

System.out.println(“Waiter: ” + emptyCup. getCapacity());

}else{

emptyCup.addWaterToCup(addSpeed);

System.out.println(“Waiter add ” + addSpeed + 

“ and current capacity is:” + emptyCup. getCapacity());

TimeUnit.SECONDS.sleep(new Random().nextInt(10));

}

}catch(InterruptedException e){

e.printStackTrack();

}

}

}

}

//顾客类

class Customer implements Runnable{

int drinkSpeed = 1;

public Customer(int drinkSpeed){

this.drinkSpeed = drinkSpeed;

}

public void run(){

while(fullCup != null){

try{

//如果杯子已空,则与服务员进行交换,顾客获得装满水的杯子

if(fullCup.isEmpty()){

fullCup = exchanger.exchanger(fullCup);

System.out.println(“Customer: ” + fullCup. getCapacity());

}else{

fullCup.drinkWaterFromCup(drinkSpeed);

System.out.println(“Customer drink ” + drinkSpeed + 

“ and current capacity is:” + fullCup.getCapacity());

TimeUnit.SECONDS.sleep(new Random().nextInt(10));

}

}catch(InterruptedException e){

e.printStackTrack();

}

}

}

}

public static void main(String[] args){

new Thread(new Waiter(3)).start();

new Thread(new Customer(6)).start();

}

}

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 编程思想 并发