标签:
1、数据库事务基础知识
Connection conn; try{ conn = DriverManager.getConnection(); conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); Statement stmt = conn.createStatement(); int rows = stmt.executeUpdate("INSERT INTO t_topic VALUES(1,‘tom‘)"); rows = stmt.executeUpdate("UPDATE t_user set topic_nums = topic_nums + 1 WHERE user_id = 1"); conn.commit(); }catch(Exception e){ ... conn.rollback(); }finally( ... )
package com.yyq.transaction; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class SimpleThreadLocal { private Map valueMap = Collections.synchronizedMap(new HashMap()); public void set(Object newValue){ valueMap.put(Thread.currentThread(),newValue); } public Object get(){ Thread currentThread = Thread.currentThread(); Object o = valueMap.get(currentThread); if (o == null && !valueMap.containsKey(currentThread)){ o = initialValue(); valueMap.put(currentThread,o); } return o; } public void remove(){ valueMap.remove(Thread.currentThread()); } public Object initialValue(){ return null; } }
一个ThreadLocal实例:
package com.yyq.transaction; public class SequenceNumber { private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() { public Integer initialValue() { return 0; } }; public int getNextNum() { seqNum.set(seqNum.get() + 1); return seqNum.get(); } private static class TestClient extends Thread { private SequenceNumber sn; public TestClient(SequenceNumber sn) { this.sn = sn; } public void run() { for (int i = 0; i < 3; i++) { System.out.println("thread[" + Thread.currentThread().getName() + "]sn[" + sn.getNextNum() + "]"); } } } public static void main(String[] args) { SequenceNumber sn = new SequenceNumber(); TestClient t1 = new TestClient(sn); TestClient t2 = new TestClient(sn); TestClient t3 = new TestClient(sn); t1.start(); t2.start(); t3.start(); } }
标签:
原文地址:http://www.cnblogs.com/yangyquin/p/5583112.html