国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ Java &#&ベース simpledateformat スレッドが安全でないのはなぜですか?

simpledateformat スレッドが安全でないのはなぜですか?

May 10, 2021 pm 02:40 PM
simpledateformat

原因: マルチスレッド環(huán)境では、format メソッドの呼び出しなど、複數(shù)のスレッドが同じ SimpleDateFormat オブジェクト (靜的変更など) を同時に使用すると、複數(shù)のスレッドが calender.setTime メソッドを呼び出します。同時に、他のスレッドによって変更される時間が発生するため、スレッドは安全ではありません。

simpledateformat スレッドが安全でないのはなぜですか?

#このチュートリアルの動作環(huán)境: Windows7 システム、Java8 バージョン、DELL G3 コンピューター。

スレッドの安全性の確認:

/**
 * SimpleDateFormat線程安全測試
 * 〈功能詳細描述〉
 *
 * @author 17090889
 * @see [相關(guān)類/方法](可選)
 * @since [產(chǎn)品/模塊版本] (可選)
 */
public class SimpleDateFormatTest {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000), new MyThreadFactory("SimpleDateFormatTest"));

    public void test() {
        while (true) {
            poolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    String dateString = simpleDateFormat.format(new Date());
                    try {
                        Date parseDate = simpleDateFormat.parse(dateString);
                        String dateString2 = simpleDateFormat.format(parseDate);
                        System.out.println(dateString.equals(dateString2));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

出力:

  true
  false
  true
  true
  false

false が表示され、スレッドが安全でないことを示します

1、形式メソッド

public StringBuffer format(Date date, StringBuffer toAppendTo,
                               FieldPosition pos)
    {
        pos.beginIndex = pos.endIndex = 0;
        return format(date, toAppendTo, pos.getFieldDelegate());
    }

    // Called from Format after creating a FieldDelegate
    private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // Convert input date to time field list
        calendar.setTime(date);

        boolean useDateFormatSymbols = useDateFormatSymbols();

        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }

            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;

            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;

            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }
 protected Calendar calendar;

変數(shù)カレンダーが複數(shù)のスレッド間で共有され、カレンダーが変更されていることがわかります。したがって、マルチスレッド環(huán)境では、format メソッドの呼び出しなど、複數(shù)のスレッドが同じ SimpleDateFormat オブジェクト (靜的変更など) を同時に使用すると、複數(shù)のスレッドが同時に calender.setTime メソッドを呼び出し、他のスレッドによって変更される可能性があるため、スレッドは安全ではありません。

さらに、parse メソッドもスレッドアンセーフです。parse メソッドは、実際には、解析のために CalenderBuilder の確立を呼び出します。メソッドの主なステップは、アトミックな操作ではありません。

解決策:

1. SimpleDateFormat をローカル変數(shù)として定義します

2. スレッド同期ロックを追加します: synchronized(lock)

3. ThreadLocal を使用すると、各スレッドは SimpleDateFormat オブジェクトの獨自のコピーを持ちます。例:

/**
 * SimpleDateFormat線程安全測試
 * 〈功能詳細描述〉
 *
 * @author 17090889
 * @see [相關(guān)類/方法](可選)
 * @since [產(chǎn)品/模塊版本] (可選)
 */
public class SimpleDateFormatTest {
        private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    //    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000), new MyThreadFactory("SimpleDateFormatTest"));

    public void test() {
        while (true) {
            poolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    SimpleDateFormat simpleDateFormat = THREAD_LOCAL.get();
                    if (simpleDateFormat == null) {
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    String dateString = simpleDateFormat.format(new Date());
                    try {
                        Date parseDate = simpleDateFormat.parse(dateString);
                        String dateString2 = simpleDateFormat.format(parseDate);
                        System.out.println(dateString.equals(dateString2));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } finally {
                        local.remove();
                    }
                }
            });
        }
    }
}

4. SimpleDateFormat の代わりに DateTimeFormatter を使用します

DateTimeFormatter はスレッドセーフであり、デフォルトで多くの書式設(shè)定メソッドを提供します。カスタムの書式設(shè)定メソッドは ofPattern メソッドを通じて作成することもできます。

(1) 日付のフォーマット例:

 LocalDateTime localDateTime = LocalDateTime.now();
 System.out.println(localDateTime); // 2019-11-20T15:04:29.017
 DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
 String strDate=localDateTime.format(dtf);
 System.out.println(strDate); // 2019/23/20 15:23:46

(2) 解析日付

 DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
 LocalDateTime localDateTime=LocalDateTime.parse("2019/11/20 15:23:46",dtf);
 System.out.println(localDateTime); // 2019-11-20T15:23:46

関連ビデオチュートリアルの推奨事項:

Java ビデオ チュートリアル

以上がsimpledateformat スレッドが安全でないのはなぜですか?の詳細內(nèi)容です。詳細については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)