我想为一些静态方法使用日历并使用静态字段:
I'd like to use a Calendar for some static methods and use a static field:
private static Calendar calendar = Calendar.getInstance();
现在我读到 java.util.Calendar 不是线程安全的.我怎样才能使这个线程安全(它应该是静态)?
Now I read java.util.Calendar isn't thread safe. How can I make this thread safe (it should be static)?
如果它不是线程安全的,你就不能做一些线程安全的东西.在 Calendar 的情况下,即使从它读取数据也不是线程安全的,因为它可以更新内部数据结构.
You can't make something thread-safe if it isn't. In the case of Calendar, even reading data from it isn't thread-safe, as it can update internal data structures.
如果可能的话,我建议改用 Joda Time:
If at all possible, I'd suggest using Joda Time instead:
如果您绝对必须使用 Calendar,则可以创建一个锁定对象并通过锁定来进行所有访问.例如:
If you absolutely have to use a Calendar, you could create a locking object and put all the access through a lock. For example:
private static final Calendar calendar = Calendar.getInstance();
private static final Object calendarLock = new Object();
public static int getYear()
{
synchronized(calendarLock)
{
return calendar.get(Calendar.YEAR);
}
}
// Ditto for other methods
虽然很恶心.您可以只使用 一个 同步方法,该方法在每次需要时创建原始日历的克隆,当然...可以通过调用 computeFields 或 computeTime 当然,您可以使 后续 读取操作线程安全,但我个人不愿意尝试它.
It's pretty nasty though. You could have just one synchronized method which created a clone of the original calendar each time it was needed, of course... it's possible that by calling computeFields or computeTime you could make subsequent read-operations thread-safe, of course, but personally I'd be loathe to try it.
这篇关于如何使静态日历线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
解析 ISO 8601 字符串本地日期时间,就像在 UTC 中Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期时间,就像在 UTC 中一样)
如何将公历字符串转换为公历?How to convert Gregorian string to Gregorian Calendar?(如何将公历字符串转换为公历?)
Java:GregorianCalendar 的最大值和最小值是什么/在哪Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
1582 年 10 月 15 日之前日期的日历到日期转换.公历Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日历到日期转换
java日历setFirstDayOfWeek不起作用java Calendar setFirstDayOfWeek not working(java日历setFirstDayOfWeek不起作用)
Java:获取当前星期几的值Java: getting current Day of the Week value(Java:获取当前星期几的值)