/**一个类中要访问多个
线程,同时又用到格式化日期类时, 格式化日期类对象不能同时访问多个线程
*访问多个线程,格式化日期类会出现意想不到的格式化
错误,一个线程只能对应一个格式化日期类
* author :wuxq date:2011-10-26
*/
package biz;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private SimpleDateFormat dateFormat;
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date today = new Date();
Date tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24);
System.out.println(today); // 今天是2011-10-27
System.out.println(tomorrow); // 明天是2010-10-28
synchronized (dateFormat) {
Thread
thread2 = new Thread(new Thread2(dateFormat, tomorrow));
thread2.start();
}
synchronized (dateFormat2) {
Thread thread1 = new Thread(new Thread1(dateFormat2, today));
thread1.start();
}
}
}
class Thread1 implements
Runnable {
private SimpleDateFormat dateFormat;
private Date date;
public Thread1(SimpleDateFormat dateFormat, Date date) {
this.dateFormat = dateFormat;
this.date = date;
}
public void run() {
for (;;) {// 一直循环到出问题为止吧。
String strDate = dateFormat.format(date);
System.out.println(strDate);
// 如果不等于2010-01-11,证明出现
线程安全问题了!!!!
if (!"2011-10-27".equals(strDate)) {
System.err.println("today=" + strDate);
System.exit(0);
}
}
}
}
class Thread2 implements Runnable {
private SimpleDateFormat dateFormat;
private Date date;
public Thread2(SimpleDateFormat dateFormat, Date date) {
this.dateFormat = dateFormat;
this.date = date;
}
public void run() {
for (;;) {
String strDate = dateFormat.format(date);
System.out.println(strDate);
if (!"2011-10-28".equals(strDate)) {
System.err.println("tomorrow=" + strDate);
System.exit(0);
}
}
}
}