import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 验证 SimpleDateFormat 是线程不安全的
*/
public class DateFormat {
/**
* 只创建一份,避免频繁地创建对象和销毁对象
* 单线程下可以不出错
* 多线程下则不安全, 不同的线程会对不同日期字符串进行解析,
* 会出现线程 A 解析到一半被挂起,线程 B 运行时将 A 的解析到一半的字符串覆盖掉,
* 这样轮到 A 运行时会解析失败,或者使用了 B 的字符串
*/
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 线程安全的 DateTimeFormatter
* 推荐使用,因为该类是不可变的,并且是线程安全的
*/
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Test
public void formatTest() {
ExecutorService service = Executors.newFixedThreadPool(10);
for(int i = 0; i < 10; i++){
service.execute(new Runnable() {
@Override
public void run() {
String dateStr = "2019-04-16 10:26:30";
// 解决方法
// 1、可以只在需要时创建对象,也可以避免错误,但是频繁创建与销毁会导致额外的开销,性能低
// SimpleDateFormat newInNeed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(int j = 0; j < 10; j++){
//
// try {
// 直接使用不但运行结果错误,最后还会抛出 NumberFormatException: 异常
// System.out.println(format.parse(dateStr));
// 2、使用加了 synchronized 的同步方法,但是并发量高时,性能影响大,线程阻塞
// System.out.println(ConcurrentDateFormat.parse(dateStr));
// 3、使用 ThreadLocal 来解决,比较优雅的一种做法
// System.out.println(ThreadLocalDateFormat.parse(dateStr));
// } catch (ParseException e) {
// e.printStackTrace();
// }
// 4、使用DateFormatter,该类是线程安全的,可以放心使用
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtf);
System.out.println(localDateTime);
}
}
});
}
}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 通过 ThreadLocal 为每个线程做一份变量副本,实现线程安全
*/
public class ThreadLocalDateFormat {
/**
* ThreadLocal 提供一种 lombda 构造方式
* 返回此线程局部变量的当前线程的“初始值”。线程第一次使用 get() 方法访问变量时将调用此方法,
* 但如果线程之前调用了 set(T) 方法,则不会对该线程再调用 initialValue 方法。通常,此方法
* 对每个线程最多调用一次,但如果在调用 get() 后又调用了 remove(),则可能再次调用此方法。
*/
private static ThreadLocal<DateFormat> threadLocal
= ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public static Date parse(String date) throws ParseException {
System.out.println(date);
return threadLocal.get().parse(date);
}
public static String format(Date date){
return threadLocal.get().format(date);
}
}
package com.qianyu.gof.iterator;
/**
* @author lijing
* @date 2019-04-10-14:37
* @discroption 迭代器接口
*/
public interface MyIterator {
/**
* 判断是否有下一个元素
*
* @return
*/
boolean hasNext();
/**
* 返回当前元素,并且将游标向下移动一位
*
* @return
*/
Object next();
}
package com.qianyu.gof.iterator;
/**
* @author lijing
* @date 2019-04-10-19:14
* @discroption 自定义迭代器测试类(迭代器模式)
*/
public class IteratorTest2 {
public static void main(String[] args) {
MyList myList = new MyList();
myList.add("aa");
myList.add("bb");
myList.add("cc");
MyIterator iter = myList.iterator();
while (iter.hasNext()){
System.out.println(iter.next());
}
}
}
public class Producter {
//ActiveMq 的默认用户名
private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
//ActiveMq 的默认登录密码
private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
//ActiveMQ 的链接地址
private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
AtomicInteger count = new AtomicInteger(0);
//链接工厂
ConnectionFactory connectionFactory;
//链接对象
Connection connection;
//事务管理
Session session;
ThreadLocal<MessageProducer> threadLocal = new ThreadLocal<>();
public void init(){
try {
//创建一个链接工厂
connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
//从工厂中创建一个链接
connection = connectionFactory.createConnection();
//开启链接
connection.start();
//创建一个事务(这里通过参数可以设置事务的级别)
session = connection.createSession(true,Session.SESSION_TRANSACTED);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendMessage(String disname){
try {
//创建一个消息队列
Queue queue = session.createQueue(disname);
//消息生产者
MessageProducer messageProducer = null;
if(threadLocal.get()!=null){
messageProducer = threadLocal.get();
}else{
messageProducer = session.createProducer(queue);
threadLocal.set(messageProducer);
}
while(true){
Thread.sleep(1000);
int num = count.getAndIncrement();
//创建一条消息
TextMessage msg = session.createTextMessage(Thread.currentThread().getName()+
"productor:我是大帅哥,我现在正在生产东西!,count:"+num);
System.out.println(Thread.currentThread().getName()+
"productor:我是大帅哥,我现在正在生产东西!,count:"+num);
//发送消息
messageProducer.send(msg);
//提交事务
session.commit();
}
} catch (JMSException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Comsumer {
private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
ConnectionFactory connectionFactory;
Connection connection;
Session session;
ThreadLocal<MessageConsumer> threadLocal = new ThreadLocal<>();
AtomicInteger count = new AtomicInteger();
public void init(){
try {
connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void getMessage(String disname){
try {
Queue queue = session.createQueue(disname);
MessageConsumer consumer = null;
if(threadLocal.get()!=null){
consumer = threadLocal.get();
}else{
consumer = session.createConsumer(queue);
threadLocal.set(consumer);
}
while(true){
Thread.sleep(1000);
TextMessage msg = (TextMessage) consumer.receive();
if(msg!=null) {
msg.acknowledge();
System.out.println(Thread.currentThread().getName()+": Consumer:我是消费者,我正在消费Msg"+msg.getText()+"--->"+count.getAndIncrement());
}else {
break;
}
}
} catch (JMSException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestMq {
public static void main(String[] args){
Producter producter = new Producter();
producter.init();
TestMq testMq = new TestMq();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Thread 1
new Thread(testMq.new ProductorMq(producter)).start();
//Thread 2
new Thread(testMq.new ProductorMq(producter)).start();
//Thread 3
new Thread(testMq.new ProductorMq(producter)).start();
//Thread 4
new Thread(testMq.new ProductorMq(producter)).start();
//Thread 5
new Thread(testMq.new ProductorMq(producter)).start();
}
private class ProductorMq implements Runnable{
Producter producter;
public ProductorMq(Producter producter){
this.producter = producter;
}
@Override
public void run() {
while(true){
try {
producter.sendMessage("Jaycekon-MQ");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class TestConsumer {
public static void main(String[] args){
Comsumer comsumer = new Comsumer();
comsumer.init();
TestConsumer testConsumer = new TestConsumer();
new Thread(testConsumer.new ConsumerMq(comsumer)).start();
new Thread(testConsumer.new ConsumerMq(comsumer)).start();
new Thread(testConsumer.new ConsumerMq(comsumer)).start();
new Thread(testConsumer.new ConsumerMq(comsumer)).start();
}
private class ConsumerMq implements Runnable{
Comsumer comsumer;
public ConsumerMq(Comsumer comsumer){
this.comsumer = comsumer;
}
@Override
public void run() {
while(true){
try {
comsumer.getMessage("Jaycekon-MQ");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
LocalDate localDate = LocalDate.of(2014, 3, 18);
int year = localDate.getYear();
Month month = localDate.getMonth();
int day = localDate.getDayOfMonth();
DayOfWeek dow = localDate.getDayOfWeek();
int len = localDate.lengthOfMonth();
boolean leap = localDate.isLeapYear();
// 使用工厂方法从系统时钟中获取当前的日期
LocalDate today = LocalDate.now();
System.out.println(String.format("year:%s\nmonth:%s\nday:%s\ndow:%s\nlen:%s\nleap:%s", year, month, day, dow, len, leap));
System.out.println(today);
结果:
year:2014
month:MARCH
day:18
dow:TUESDAY
len:31
leap:false
2019-03-27
LocalDate date = LocalDate.of(2019, 03, 27);
ZonedDateTime zdt1 = date.atStartOfDay(shanghaiZone);
LocalDateTime dateTime = LocalDateTime.of(2015, 12, 21, 11, 11, 11);
ZonedDateTime zdt2 = dateTime.atZone(shanghaiZone);
Instant instant = Instant.now();
ZonedDateTime zdt3 = instant.atZone(shanghaiZone);
通过ZoneId,你还可以将LocalDateTime转换为Instant:
LocalDateTime dateTime = LocalDateTime.of(2016, 10, 14, 15, 35);
Instant instantFromDateTime = dateTime.toInstant(shanghaiZone);
你也可以通过反向的方式得到LocalDateTime对象:
Instant instant = Instant.now();
LocalDateTime timeFromInstant = LocalDateTime.ofInstant(instant, shanghaiZone);
package verify.inheirt;
/*
* s为父类和子类中重名的public属性
*/
public class SamePublicFieldInInherit extends SuperClass2{
// 重名的属性
public String s = "subClassField";
public static void main(String[] args) {
// TODO Auto-generated method stub
SamePublicFieldInInherit subObject = new SamePublicFieldInInherit();
/*
* 通过.直接获取属性s,而不是方法
*/
//原始的子类对象的属性s为subClassField,读的是子类的值
System.out.println("原始的子类对象的属性s = " + subObject.s);
SuperClass2 supObject = subObject;
//子类对象转换为父类对象变量后的属性s为superClassField,读的是父类的值
System.out.println("子类对象转换为父类对象变量后的属性s = " + supObject.s);
SamePublicFieldInInherit subObject2 = (SamePublicFieldInInherit) supObject;
//再次转换回子类对象变量后的属性s为subClassField,读的又是子类的值
System.out.println("再次转换回子类对象变量后的属性s = " + subObject2.s);
System.out.println();
/*
*
* 实际情况中,属性不太可能是public的
多数情况,属性是被隐藏的,即无法通过.直接访问,需要通过get方法获取,
若此时出现这样的重名情况,则必须通过重写get方法来保证无论怎么转换对象变量,
我们读到的始终都是子类的值
下面演示的就是通过重写的get方法来访问属性s,打印的结果都为subClassField
*/
System.out.println("方法获取的:最初始的属性为 " + subObject.getS());
System.out.println("方法获取的:转换为父类后的属性为 " + supObject.getS());
System.out.println("方法获取的:再次转换回子类后的属性为" + supObject.getS());
}
// 重写属性s的get方法
public String getS() {
return s;
}
}
class SuperClass2 {
// 重名的属性
public String s = "superClassField";
// 属性s的get方法
public String getS() {
return s;
}
}