享元模式,共享存储高可用对象,避免多次建立,浪费内存。就是有个成员变量存储了共享的东西。
一、integer(-Djava.lang.Integer.IntegerCache.high=250 虚拟机参数可动态设置)
int a = 5;
int b = 5;
Integer i = Integer.valueOf(5);
Integer l = Integer.valueOf(5);
Integer j = Integer.valueOf(129);
Integer k = Integer.valueOf(129);
System.out.print(a == b);
System.out.print(a == i);
System.out.print(i == l);
System.out.print(j == k);
二、string
String m = "a";
String n = "a";
String h = new String("a");
String o = new String("a");
System.out.print(m == n);
System.out.print(h == o);
三、线程池
public class Connection{
public Connection(){
System.out.println("connection 构建完成");
}
}
public class ConnectionPool{
final java.util.ArrayList<Connection> connections;
public ConnectionPool(){
this.connections = new java.util.ArrayList<Connection>();
for(int i=0;i<5;i++){
connections.add(new Connection());
}
}
public Connection getConnection(){
Connection connection;
synchronized(connections){
if(connections.size()<=0){
try {
connections.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
connection = connections.remove(connections.size()-1);
connections.notify();
}
return connection;
}
public void release(Connection connection){
synchronized(connections){
if(connections.size()>=5){
try {
connections.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
connections.add(connection);
connections.notify();
}
}
}
public class RR implements Runnable{
ConnectionPool connectionPool;
int i;
public RR(ConnectionPool connectionPool,int i){
this.connectionPool = connectionPool;
this.i = i;
}
@Override
public void run() {
for(;;){
Connection connection = connectionPool.getConnection();
System.out.println(i+" getConnection");
try {
Thread.sleep(1000);
System.out.println(i+" sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
connectionPool.release(connection);
System.out.println(i+" release");
}
}
}
public static void main(String[] args) throws Exception {
ConnectionPool connectionPool =new test().new ConnectionPool();
new Thread(new test().new RR(connectionPool,1)).start();
new Thread(new test().new RR(connectionPool,2)).start();
new Thread(new test().new RR(connectionPool,3)).start();
new Thread(new test().new RR(connectionPool,4)).start();
//
//享元模式,共享存储高可用对象,避免多次建立,浪费内存
}