Properties类和单例模型总结

本文总结了Java中的Properties类,包括其包位置、类结构、配置文件的使用和解析过程。此外,深入探讨了设计模式中的单例模型,解释了单例模式的概念,分析了懒汉模式的线程安全问题及其解决方案,如使用ReentrantLock或synchronized关键字,并介绍了饿汉模式的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Properties类

1.1包

java.util.Properties

1.2类结构

public class Properties extends Hashtable<Object,Object>

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;

/**
 * 单例模型-懒汉模式
 * 
 * @author Administrator
 *
 */
public class Singleton {

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

	private Singleton() {

	}

	/**
	 * 调用getIntance()方法,才建立instance的引用对象
	 * 
	 * @return
	 */
	public static Singleton getIntance() {

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

	}

}

2.4 饿汉模式

package com.dyit.singleton;

/**
 * 单例:饿汉模式
 * @author Administrator
 *
 */
public class Singleton2 {
	
	private final static Singleton2 instance
	= new Singleton2();//JVM保证线程安全
	
	private Singleton2() {}
	
	
	public static Singleton2 getIntance() {
		return instance;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值