??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲第一视频网,久久久www免费人成精品,国产a级全部精品http://www.aygfsteel.com/freeman1984/category/49019.html STANDING ON THE SHOULDERS OF GIANTSzh-cnWed, 19 Oct 2011 11:28:06 GMTWed, 19 Oct 2011 11:28:06 GMT60Condition http://www.aygfsteel.com/freeman1984/archive/2011/10/17/361462.html@joe@joeMon, 17 Oct 2011 09:28:00 GMThttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361462.htmlhttp://www.aygfsteel.com/freeman1984/comments/361462.htmlhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361462.html#Feedback0http://www.aygfsteel.com/freeman1984/comments/commentRss/361462.htmlhttp://www.aygfsteel.com/freeman1984/services/trackbacks/361462.htmlConditionQ条Ӟ(j) ?Object 监视器方法(wait?code>notify ?notifyAllQ分解成截然不同的对象,以便通过这些对象与L Lock 实现l合使用Qؓ(f)每个对象提供多个{待 set Qwait-setQ。其中,Lock 替代?synchronized Ҏ(gu)和语句的使用Q?tt>Condition 替代?Object 监视器方法的使用?
下面解释?font face="Courier New">Condition api里面的例?生者,消费?Q?br />

public class ConditionTest {

 final Lock lock = new ReentrantLock();
     final Condition notFull  = lock.newCondition(); //生者的前提条gQ没有达到次条g阻?br />     final Condition notEmpty = lock.newCondition(); //消费者的前提条gQ没有达到次条g阻?br />  
     final Object[] items = new Object[100];
     int putptr, takeptr, count;
  //生
     public void put(Object x) throws InterruptedException {
       lock.lock();
       try {
         while (count == items.length)//如果满了(jin)Q就让需要条件ؓ(f)Q没满的的线E?生?{?br />           notFull.await();
         items[putptr] = x;
         if (++putptr == items.length) putptr = 0;
         ++count;
         notEmpty.signal();//如果已经生?jin),p需要条件ؓ(f)不ؓ(f)I的U程(消费?执行
       } finally {
         lock.unlock();
       }
     }
  //消费
     public Object take() throws InterruptedException {
       lock.lock();
       try {
         while (count == 0)//如果为空p需要条件ؓ(f)不ؓ(f)I的U程(消费?{?br />           notEmpty.await();
         Object x = items[takeptr];
         if (++takeptr == items.length) takeptr = 0;
         --count;
         notFull.signal();//如果消费?jin),p条gZ满的U程(生?执行
         return x;
       } finally {
         lock.unlock();
       }
     }
   }

 



@joe 2011-10-17 17:28 发表评论
]]>
ReadWriteLockhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361454.html@joe@joeMon, 17 Oct 2011 08:59:00 GMThttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361454.htmlhttp://www.aygfsteel.com/freeman1984/comments/361454.htmlhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361454.html#Feedback0http://www.aygfsteel.com/freeman1984/comments/commentRss/361454.htmlhttp://www.aygfsteel.com/freeman1984/services/trackbacks/361454.html  冲jdk1.5开始可以用ReadWriteLockcL防止d冲突.它有一个已有的实现ReentrantReadWriteLock?br />ReentrantReadWriteLock使用内部l护的读写锁来防止读写冲H;
 
  public ReentrantReadWriteLock.WriteLock writeLock() return writerLock; }
    
public ReentrantReadWriteLock.ReadLock  readLock()  return readerLock; }
CZ代码如下Q?br />

public class RreadWriteLockTest {

  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  public int i  = 0;
//d
 public void read() throws InterruptedException{
  readWriteLock.readLock().lock();//获取读锁
  System.out.println("read thread:"+Thread.currentThread().getName());
  Thread.sleep(10000);
  System.out.println("read:"+i);
  readWriteLock.readLock().unlock();
 }
//写入
 public void write() throws InterruptedException{
  
  readWriteLock.writeLock().lock();//获取写锁
  System.out.println("write thread:"+Thread.currentThread().getName());
  Thread.sleep(10000);
  i = 2;
  System.out.println("write:"+i);
readWriteLock.writeLock().unlock();
 }
}
试代码Q?br />1 试两个同时ȝQ结果都能同时读取?br />2 试一个读Q一个写的,需要其中一个释N之后才能q行另外一个操?br />public static void main(String[] args) throws InterruptedException {
  final RreadWriteLockTest lockTest= new RreadWriteLockTest();
  new Thread(new Runnable() {
   
   @Override
   public void run() {
    try {
     lockTest.write();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }).start();
  Thread.sleep(2000);
 new Thread(new Runnable() {
    @Override
    public void run() {
     try {
      lockTest.read();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }).start();
 }
打印如下Q?br />write thread:Thread-0执行完之?10U之?才执行read thread:Thread-1

注意Q执行完以后一定要执行unlockQ要不lock的计数没?1Q这样对应read或者write的操作将无法q行Q一直等待?/span>



@joe 2011-10-17 16:59 发表评论
]]>
synchronized 要注意的地方http://www.aygfsteel.com/freeman1984/archive/2011/10/17/361403.html@joe@joeMon, 17 Oct 2011 02:56:00 GMThttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361403.htmlhttp://www.aygfsteel.com/freeman1984/comments/361403.htmlhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361403.html#Feedback0http://www.aygfsteel.com/freeman1984/comments/commentRss/361403.htmlhttp://www.aygfsteel.com/freeman1984/services/trackbacks/361403.html在Java1.5之前Qsynchronized应该是最常用的java支持q发手段。那synchronized是怎么做到的了(jin)Q从java1.0开始,java中的每个对象׃个内部锁。如果一个类的方法被synchronized关键字所修饰Q那么这个对象的锁将保护整个Ҏ(gu)?/p>

举例来说Q?/p>

public synchronized void method(){

    method body

}

{h(hun)?/p>

public void method(){

    this.intrinsicLock.lock();

    try{

        method body;

    }finally(){

        this.intrinsicLock.unlock();

    }

}

 

从上面的代码CZ可以看出Qsynchronized的用方式是比较单的。这也导致了(jin)大量的初学者在到java~程的时候落入陷阱里Q认为既然synhronized可以搞定一切,那么不管三七二十一Q只要有q发可能性的地方Q就加上synchronized的关键字Q这昄是不对的。在java对象中,q个java对象只有q一个内部锁Q其中一个synchronizedҎ(gu)获取C(jin)q个锁,另外一个synchronizedҎ(gu)的调用将被阻塞?/p>

?/p>

class sync{

    public synchronized void methodA(){};

    public synchronized void methodB(){};

    ... ...

 

}

methodA 和methodB在初始就是互斥的Q如果methodA和methodBq入互相{待Q就很容易出现死锁的情况。那如果到q种情况Q应该怎么做了(jin)Q常用的方式是在Ҏ(gu)内部新徏一个无意义的对象,然后对这个无意义的对象加锅?/p>

 

  1. package zl.study.concurrency.synchronize;  
  2. public class Sync {  
  3.     private int i;  
  4.       
  5.     public void plus(){  
  6.         Object dummy = new Object();  
  7.         synchronized(dummy){  
  8.             i++;  
  9.         }  
  10.     }  
  11.       
  12.     public void minus(){  
  13.         Object dummy = new Object();  
  14.         synchronized(dummy){  
  15.             i--;  
  16.         }         
  17.     }  
  18. }  
 

另外需要注意的是将?rn)态类声明为synchronizedҎ(gu)也是合法的。D例来_(d)如果Sync有一个static synchronizedҎ(gu)Q那么这个方法被调用?bank.classq个cd象本w在jvm中将被锁?/p>

@joe 2011-10-17 10:56 发表评论
]]>
AtomicIntegerhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361402.html@joe@joeMon, 17 Oct 2011 02:53:00 GMThttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361402.htmlhttp://www.aygfsteel.com/freeman1984/comments/361402.htmlhttp://www.aygfsteel.com/freeman1984/archive/2011/10/17/361402.html#Feedback0http://www.aygfsteel.com/freeman1984/comments/commentRss/361402.htmlhttp://www.aygfsteel.com/freeman1984/services/trackbacks/361402.html

AtomicIntegerQ一个提供原子操作的Integer的类。在Java语言中,++i和i++操作q不是线E安全的Q在使用的时候,不可避免的会(x)用到synchronized关键字。而AtomicInteger则通过一U线E安全的加减操作接口?/p>

来看AtomicInteger提供的接口?/p>

//获取当前的?/p>

public final int get()

//取当前的|q设|新的?/p>

 public final int getAndSet(int newValue)

//获取当前的|q自?/p>

 public final int getAndIncrement()

//获取当前的|q自?/p>

public final int getAndDecrement()

//获取当前的|q加上预期的?/p>

public final int getAndAdd(int delta)

... ...

我们在上一节提到的CAS主要是这两个Ҏ(gu)

    public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

    public final boolean weakCompareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

q两个方法是名称不同Q但是做的事是一L(fng)Q可能在后箋(hu)的java版本里面?x)显C出区别来?/p>

详细查看?x)发玎ͼq两个接口都是调用一个unsafe的类来操作,q个是通过JNI实现的本地方法,l节׃考虑?jin)?/p>

 

下面是一个对比测试,我们写一个synchronized的方法和一个AtomicInteger的方法来q行试Q直观的感受下性能上的差异

 

 
  1. package zl.study.concurrency;  
  2. import java.util.concurrent.atomic.AtomicInteger;  
  3. public class AtomicIntegerCompareTest {  
  4.     private int value;  
  5.       
  6.     public AtomicIntegerCompareTest(int value){  
  7.         this.value = value;  
  8.     }  
  9.       
  10.     public synchronized int increase(){  
  11.         return value++;  
  12.     }  
  13.       
  14.     public static void main(String args[]){  
  15.         long start = System.currentTimeMillis();  
  16.           
  17.         AtomicIntegerCompareTest test = new AtomicIntegerCompareTest(0);  
  18.         forint i=0;i< 1000000;i++){  
  19.             test.increase();  
  20.         }  
  21.         long end = System.currentTimeMillis();  
  22.         System.out.println("time elapse:"+(end -start));  
  23.           
  24.         long start1 = System.currentTimeMillis();  
  25.           
  26.         AtomicInteger atomic = new AtomicInteger(0);  
  27.           
  28.         forint i=0;i< 1000000;i++){  
  29.             atomic.incrementAndGet();  
  30.         }  
  31.         long end1 = System.currentTimeMillis();  
  32.         System.out.println("time elapse:"+(end1 -start1) );  
  33.           
  34.           
  35.     }  
  36. }  

 

l果

time elapse:31
time elapse:16
由此不难看出Q通过JNI本地的CAS性能q超synchronized关键?/p>

 

Reference

http://stackoverflow.com/questions/2443239/java-atomicinteger-what-are-the-differences-between-compareandset-and-weakcompar



@joe 2011-10-17 10:53 发表评论
]]>
CountDownLatch 介和例子http://www.aygfsteel.com/freeman1984/archive/2011/07/04/353654.html@joe@joeMon, 04 Jul 2011 09:14:00 GMThttp://www.aygfsteel.com/freeman1984/archive/2011/07/04/353654.htmlhttp://www.aygfsteel.com/freeman1984/comments/353654.htmlhttp://www.aygfsteel.com/freeman1984/archive/2011/07/04/353654.html#Feedback0http://www.aygfsteel.com/freeman1984/comments/commentRss/353654.htmlhttp://www.aygfsteel.com/freeman1984/services/trackbacks/353654.html  CountDownLatchcL一个同步倒数计数?构造时传入int参数,该参数就是计数器的初始|每调用一ơcountDown()Ҏ(gu)Q计数器?,计数器大? Ӟawait()Ҏ(gu)?x)阻塞后面程序执行,直到计数器?f)0Qawait(long timeout, TimeUnit unit)Q是{待一定时_(d)然后执行Q不计数器是否??jin)?br />下面举一个等车的例子Q?br />10个同学上车,车等待同学上车,如果有等待时间限Ӟ到时间就开赎ͼ不管学生上没上完。如果没有等待时_(d)学生上完?jin)再开Q?
public class CountDownLatchTest {
    
public static int numberOfPeople = 10;//{R的学生数
    public static boolean isGone = false;//车开的标?/span>
    public static int carWaitTime = 3;//车等的时?/span>
    
    
public static void main(String[] args) throws InterruptedException {
        
        CountDownLatch waitStudentsGetOn 
= new CountDownLatch(numberOfPeople);
        
        
new Thread(new GetOn(waitStudentsGetOn)).start();
        
        waitStudentGetOn(waitStudentsGetOn);
//{所有的学生上R
        
        driveHome();
//开车走
        
    }

    
    
private static void waitStudentGetOn(CountDownLatch waitStudentsGetOn) throws InterruptedException {
        System.out.println(
"赶紧?抓紧旉上R..");
        waitStudentsGetOn.await(carWaitTime, TimeUnit.SECONDS);
//{?U,q没上RQ就开走。?/span>
        
    }


    
private static void driveHome() throws InterruptedException {
        System.out.println(
"开车,鞋儿?nbsp;帽儿?nbsp;w上的袈裟破 你笑?nbsp;他笑?nbsp;一把扇儿破");
        isGone 
= true;
        
    }

    
}

class GetOn implements Runnable{
    
    
private CountDownLatch waitStudentsGetOn;
    GetOn(CountDownLatch waitStudentsGetOn)
{
        
this.waitStudentsGetOn = waitStudentsGetOn;
    }

    
public void run() {
        
for (int i = 0; i < CountDownLatchTest.numberOfPeople; i++{
            
try {
                
if(CountDownLatchTest.isGone){
                    System.out.println(
"妈的Q还差:(x)"+waitStudentsGetOn.getCount()+" 个没娃上车呢.怎么车走?/span>");
                    
break;
                }

                
boolean goonSuccess = new Student(i+1).getOn();//序上R
                if(goonSuccess)waitStudentsGetOn.countDown();
            }
 catch (InterruptedException e) {}
                
if(waitStudentsGetOn.getCount()!=0l){
                    System.out.println(
"q差Q?/span>"+(waitStudentsGetOn.getCount())+" 个没上R");
                }
else{
                    System.out.println(
"都上车了(jin)");
                }

        }

        
        
    }

    
class Student{
        
private int myNum;//学生~号
         public Student(int num){
                
this.myNum = num;
          }

         
//上R
         public boolean getOn() throws InterruptedException{
             Thread.currentThread().sleep(
new Random().nextInt(2)*1000);//上R使用的时_(d)随机
             if(CountDownLatchTest.isGone){
                 
return false;//不能上了(jin)Q上车失?/span>
             }

             System.out.print(
"~号?"+myNum+"的同学上车了(jin)..");
             
return true;
         }

    }

}



@joe 2011-07-04 17:14 发表评论
]]>
վ֩ģ壺 | | | | | ϻ| | | ǿ| ɽ| ֶ| ī| ʯ| | ͨ| | Թ| | Ϻ| | ˮ| | | »| | ɽ| | | ͷ| ƽ| | ϰ| û| | Ϣ| ؿ˹| | | | ƽ| |