栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Properties类和单例模型总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Properties类和单例模型总结

文章目录

1.Properties类

1.1包1.2类结构1.3配置文件1.4解析 2.设计模式-单例模型

2.1 什么是单例?2.2 懒汉模式的线程安全问题

2.3 线程安全解决方案 2.4 饿汉模式

1.Properties类 1.1包

java.util.Properties

1.2类结构
public class Properties extends Hashtable
1.3配置文件

resources/user.properties

user.username = admin
user.password = 223
1.4解析
Properties prop = new Properties();

String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String fileName = path+"com/dyit/resources/user.properties";
prop.load(new FileReader(fileName));
System.out.println("用户名: " + prop.getProperty("user.username"));
System.out.println("密码: " + prop.getProperty("user.password"));
2.设计模式-单例模型 2.1 什么是单例?

创建型模式: 创建对象·

核心: 内存中只有唯一的一个对象

2.2 懒汉模式的线程安全问题
Executor pool = Executors.newCachedThreadPool();

		for (int i = 0; i < 10; i++) {
			pool.execute(() -> {
				for (int j = 0; j < 10; j++) {
					System.out.println(Thread.currentThread().getName() + ": " + Singleton.getIntance().hashCode());
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
pool-1-thread-6: 1335324870
pool-1-thread-10: 1335324870
pool-1-thread-1: 1967528551
pool-1-thread-8: 1335324870
pool-1-thread-4: 2087870959
pool-1-thread-9: 1335324870
pool-1-thread-7: 1335324870
2.3 线程安全解决方案

ReentrantLock/synchronized

package com.dyit.singleton;

import java.util.concurrent.locks.ReentrantLock;

import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;


public class Singleton {

	private static Singleton instance = null; // instance 一开始没有引用任何对象
	private final static ReentrantLock lock = new ReentrantLock();

	private Singleton() {

	}

	
	public static Singleton getIntance() {

		lock.lock();
		try {
			if (instance == null) {
				instance = new Singleton();
			}
		} finally {
			lock.unlock();
		}
		return instance;

	}

}

2.4 饿汉模式
package com.dyit.singleton;


public class Singleton2 {
	
	private final static Singleton2 instance
	= new Singleton2();//JVM保证线程安全
	
	private Singleton2() {}
	
	
	public static Singleton2 getIntance() {
		return instance;
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759613.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号