クラス UnSafeTask を作成しました。
package com.threads;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class UnsafeTask implements Runnable {
private Date startDate;
@Override
public void run() {
startDate = new Date();
System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
try {
TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
}
}
以下のようにコアクラスで使用しました。
package com.threads;
import java.util.concurrent.TimeUnit;
public class Core {
public static void main(String[] args) {
UnsafeTask task = new UnsafeTask();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(task);
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
結果は期待どおりです (変数はスレッドによって共有されます)。匿名の実行可能なクラスを使用するために次のようにコアをリファクタリングしたとき:
package com.threads;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Core {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
Date startDate = new Date();
@Override
public void run() {
startDate = new Date();
System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
try {
TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
これで、変数 (startDate) はスレッド セーフになりました。この場合、変数がスレッドセーフなのはなぜですか? 前もって感謝します。