1。スレッドの安全性の問題の原因
スレッドの安全性の問題は、グローバル変数と静的変数によって引き起こされます。
2。スレッドの安全性の問題
SimpleDateFormate sdf = new SimpledateFormat(); sdf.parse(datestr)を使用してください。 sdf.format(date); sdf.parse(datestr)にはCaleadarオブジェクトへの参照があります。ソースコードでは、calendar.clear();およびcalendar.getTime(); //カレンダーの時間を取得します
スレッドaはsdf.parse()を呼び出し、calendar.gettime()をまだ実行していない場合、calendar.clear()の後にスレッドbを呼び出してsdf.parse()を呼び出し、スレッドBはsdf.clear()メソッドも実行します。これにより、スレッドAのカレンダーデータがクリアされます。
Threadlocalはスペースを使用して時間を交換し、同期した時間を使用してスペースを交換します
threadlocalを使用して、スレッドの安全性を解決します。
public class threadlocaldateutil {private static final string date_format = "yyyy-mm-dd hh:mm:ss"; private static threadlocal <dateformat> threadlocal = new threadlocal <dateformat>(); public static dateformat getDateFormat(){dateFormat df = threadlocal.get(); if(df == null){df = new SimpledateFormat(date_format); threadlocal.set(df); } dfを返します。 } public static string formatdate(date date)throws parseexception {return getDateFormat()。format(date); } public static date parse(string strdate)throws parseexception {return getDateFormat()。parse(strdate); }}同期ソリューションの使用:
public class datesyncutil {private static simpledateformat sdf = new simpledateFormat( "yyyy-mm-dd hh:mm:ss"); public static string formatdate(日付)スローparseexception {synchronized(sdf){return sdf.format(date); }} public static date parse(string strdate)throws parseexception {synchronized(sdf){return sdf.parse(strdate); }}}この記事を読んでくれてありがとう、私はそれがあなたを助けることができることを願っています。このウェブサイトへのご支援ありがとうございます!