共享信号资源
package com.example.BankExample; import java.util.Random; import java.util.concurrent.Semaphore; public class SharedResource { private final Semaphore semaphore; private final int permits; private final static Random rndom=new Random(314159); public SharedResource(int permits) { this.semaphore = new Semaphore(permits); this.permits=permits; } public void use() throws InterruptedException{ semaphore.acquire(); try{ doUse(); } finally { semaphore.release(); } } protected void doUse() throws InterruptedException{ Log.println("Begin:used"+(permits-semaphore.availablePermits())); Thread.sleep(rndom.nextInt(500)); Log.println("End:used"+(permits-semaphore.availablePermits())); } static class Log{ public static void println(String s){ System.out.println(Thread.currentThread().getName()+":"+s); } } }使用共享信号资源的线程
**package com.example.BankExample; import java.util.Random; public class SemaphereThread extends Thread{ private static final Random rdandom=new Random(26535); private final SharedResource resource; public SemaphereThread(SharedResource resource){ this.resource =resource; } public void run(){ try{ while (true){ resource.use(); Thread.sleep(rdandom.nextInt(3000)); } }catch (InterruptedException e){} } }测试
package com.example.test; import com.example.BankExample.SemaphereThread; import com.example.BankExample.SharedResource; public class TestSemaphere { public static void main(String[] args){ SharedResource resource=new SharedResource(3); for(int i=0;i<10;i++){ new SemaphereThread(resource).start(); } } }如果一个类是Immutable的那么这个类就是线程安全的,类中的字段是Frozen 方法是并发安全的Concurrent,类是final的不能创建(派生)子类,字段是final的,只能在构造方法或者初始化赋值,没有set方法,final方法不能重写。合理使用此类型的类可以提高性能。single thread 锁有read-write 和write write的冲突限制,read-write Lock利用read-read不会冲突的特点,将read和write分开,提高性能。immutable也利用read-read不会冲突特点,提高性能。Immutable类包括String BigInteger Boolean Byte Character Double Integer Long Short Void。
package com.example.BankExample; public final class ImmutableDemo { private final String name; public ImmutableDemo(String name){ this.name=name; } public String getName(){ return name; } public String toString(){ return name; } }测试Immutable的性能提升
package com.example.test; public class TestImmutable { private static final long Call_Count=100000000L; public static void main(String args[]){ trial("NotSynch",Call_Count,new NotSynch()); trial("Synch",Call_Count,new Synch()); } private static void trial(String msg,long count,Object obj){ System.out.println(msg+":Begin"); long start_time=System.currentTimeMillis(); for(long i=0;i<count;i++){ obj.toString(); } System.out.println(msg+":end"); System.out.println("cost"+(System.currentTimeMillis()-start_time)+"msec"); } } class NotSynch{ private final String name="NotSynch"; public String toString(){ return "["+name+"]"; } } class Synch{ private final String name="Synch"; public synchronized String toString(){ return "["+name+"]"; } }结果: NotSynch:Begin NotSynch:end cost31msec Synch:Begin Synch:end cost1717msec