1.都是为了解决度线程中相同变量的访问冲突问题
2.synchronized同步机制,提供一份变量,让不同的线程排队访问
3.ThreadLocal关键字,为每一个线程都提供了一份变量,因此可以同时访问而互不影响.
4.ThreadLocal比直接使用synchronized同步机制解决线程安全问题更加单,更方便,且结果程序拥有更高的并发性.
辅助理解
ThreadLocal
public class ConnectionUtil {
private static ThreadLocal tl = new ThreadLocal();
private static Connection initConn = null;
static {
try {
initConn = DriverManager.getConnection(“url, name and password”);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConn() {
Connection c = tl.get();
if(null == c) tl.set(initConn);
return tl.get();
}
}
synchronized
public class ConnectionUtil {
private static DBOPool instance=null;
public static synchronized Connection getInstance(){
if(instance==null)
instance=new DBOPool();
return instance.getConnection();
}
}