标签:des style blog class c code
Subsections
线程安全(Thread safety)
锁(lock)
共享对象
对象组合
基础构建模块
任务执行
取消和关闭
线程池的使用
性能与可伸缩性
并发程序的测试
显示锁
原子变量和非阻塞同步机制
public class Instance() { private Instance in = null; public Instance getInstance() { if(in == null) { in= new Instance(); } return in; } }
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); }
//如果是第一次调用,需要初始化。
private T setInitialValue() { T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); return value; }//将此线程局部变量的当前线程副本中的值设置为指定值
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }//移除此线程局部变量的值。
public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }数据库连接管理类,转载:http://blog.csdn.net/ghsau/article/details/15732053
public class ConnectionManager { /** 线程内共享Connection,ThreadLocal通常是全局的,支持泛型 */ private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>(); public static Connection getCurrConnection() { // 获取当前线程内共享的Connection Connection conn = threadLocal.get(); try { // 判断连接是否可用 if(conn == null || conn.isClosed()) { // 创建新的Connection赋值给conn(略) // 保存Connection threadLocal.set(conn); } } catch (SQLException e) { // 异常处理 } return conn; } /** * 关闭当前数据库连接 */ public static void close() { // 获取当前线程内共享的Connection Connection conn = threadLocal.get(); try { // 判断是否已经关闭 if(conn != null && !conn.isClosed()) { // 关闭资源 conn.close(); // 移除Connection threadLocal.remove(); conn = null; } } catch (SQLException e) { // 异常处理 } } }
public class PersonSet{ private final Set<Person> mySet = new HashSet<Person>(); public sychronized void addPersion(Person p) { mySet.add(p) } public sychronized boolean containsPerson(Person p) { return mySet.contains(p); } }
public class privateLock { private final Object myLock = new Object(); private int weight; void someMethod() { synchronized(myLock) { //访问weight } } }使用私有锁对象比使用对象的内置锁有许多优点。私有锁可以将锁封装起来,客户代码无法得到锁。但客户可以通过公有方法来访问锁。以便参与到同步策略中去。
package my.concurrent.semaphore; import java.util.concurrent.Semaphore; public class Car implements Runnable { private final Semaphore parkingSlot; private int carNo; /** * @param parkingSlot * @param carName */ public Car(Semaphore parkingSlot, int carNo) { this.parkingSlot = parkingSlot; this.carNo = carNo; } public void run() { try { parkingSlot.acquire(); parking(); sleep(300); parkingSlot.release(); leaving(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void parking() { System.out.println(String.format("%d号车泊车", carNo)); } private void leaving() { System.out.println(String.format("%d号车离开车位", carNo)); } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package my.concurrent.semaphore; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class ParkingCars { private static final int NUMBER_OF_CARS = 30; private static final int NUMBER_OF_PARKING_SLOT = 10; public static void main(String[] args) { /* * 采用FIFO, 设置true */ Semaphore parkingSlot = new Semaphore(NUMBER_OF_PARKING_SLOT, true); ExecutorService service = Executors.newCachedThreadPool(); for (int carNo = 1; carNo <= NUMBER_OF_CARS; carNo++) { service.execute(new Car(parkingSlot, carNo)); } sleep(3000); service.shutdown(); /* * 输出还有几个可以用的资源数 */ System.out.println(parkingSlot.availablePermits() + " 个停车位可以用!"); } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
class singleThreadWebServer { ServerSocket socket = new ServerSocket(80) ; while (true) { Socket connection = socket.accept(); handleRequest(connection); } }
class MultiThreadWebServer { ServerSocket socket = new ServerSocket(80) ; while (true) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handleRequest(connection); } } new Thread(task).start(); } }
ExecutorService service = Executors. newFixedThreadPool(3); for ( int i = 0; i < 10; i++) { System. out.println( "创建线程" + i); Runnable run = new Runnable() { @Override public void run() { System. out.println( "启动线程"); } }; // 在未来某个时间执行给定的命令 service.execute(run); } // 关闭启动线程 service.shutdown(); // 每隔1秒监测一次ExecutorService的关闭情况. service.awaitTermination(1, TimeUnit. SECONDS); System. out.println( "all thread complete"); System. out.println(service.isTerminated());
public class CASCount implements Runnable { private SimilatedCAS counter = new SimilatedCAS(); @Override public void run() { for (int i = 0; i < 10000; i++) { System.out.println(this.increment()); } } public int increment() { int oldValue = counter.getValue(); int newValue = oldValue + 1; while (!counter.compareAndSwap(oldValue, newValue)) { //如果CAS失败,就去拿新值继续执行CAS oldValue = counter.getValue(); newValue = oldValue + 1; } return newValue; } public static void main(String[] args) { Runnable run = new CASCount(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); } } class SimilatedCAS { private int value; public int getValue() { return value; } // 这里只能用synchronized了,毕竟无法调用操作系统的CAS public synchronized boolean compareAndSwap(int expectedValue, int newValue) { if (value == expectedValue) { value = newValue; return true; } return false; } }
public class AtomicCounter implements Runnable{ //AtomicInteger采用了系统的CAS private AtomicInteger value = new AtomicInteger(); @Override public void run() { for (int i = 0; i < 10000; i++) { System.out.println(value.incrementAndGet()); } } public static void main(String[] args) { Runnable run = new AtomicCounter(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); new Thread(run).start(); } }
public class ConcurrentStack { class Node { public final int item; public Node next; public Node(int item) { this.item = item; } } private AtomicReference<Node> top = new AtomicReference<ConcurrentStack.Node>(); //入栈 public void push(int item) { Node newNode = new Node(item); Node oldHead; do { oldHead = top.get(); newNode.next = oldHead; } while (!top.compareAndSet(oldHead, newNode)); } //出栈 public int pop() { Node oldHead; Node newHead; do { oldHead = top.get(); if(oldHead == null ) { return -1; } newHead = oldHead.next; //Atomically sets the value to the given updated value if the current value {@code ==} the expected value. } while (!top.compareAndSet(oldHead, newHead)); return oldHead.item; } }
《Java并发编程实战》读书笔记,布布扣,bubuko.com
标签:des style blog class c code
原文地址:http://blog.csdn.net/cdl2008sky/article/details/26377433