多线程多个实例

时间:2022-09-24 18:21:01

一、顺序打印3次ABC

  正常的情况下,线程在运行时多个线程之间执行任务的时机是无序的。可以通过改造代码的方式使它们运行具有有序性。

public class MyThread extends Thread {
private Object lock;
private String showChar;
private int showNumPosition;
private int printCount = 0; //统计打印了几个字母

private volatile static int addNumber = 1;

public MyThread(Object lock, String showChar, int showNumPosition) {
super();
this.lock = lock;
this.showChar = showChar;
this.showNumPosition = showNumPosition;
}

@Override
public void run() {
try {
synchronized (lock) {
while (true) {
if (addNumber % 3 == showNumPosition) {
System.out.println("ThreadName="
+ Thread.currentThread().getName()
+ ",runCount=" + addNumber + " " + showChar);
lock.notifyAll();
addNumber++;
printCount++;
if (printCount == 3) {
break;
}
} else {
lock.wait();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
MyThread a = new MyThread(lock, "AA", 1);
MyThread b = new MyThread(lock, "BB", 2);
MyThread c = new MyThread(lock, "CC", 0);
a.start();
b.start();
c.start();
}
}

ThreadName=Thread-0,runCount=1 AA
ThreadName=Thread-1,runCount=2 BB
ThreadName=Thread-2,runCount=3 CC
ThreadName=Thread-0,runCount=4 AA
ThreadName=Thread-1,runCount=5 BB
ThreadName=Thread-2,runCount=6 CC
ThreadName=Thread-0,runCount=7 AA
ThreadName=Thread-1,runCount=8 BB
ThreadName=Thread-2,runCount=9 CC


二、SimpleDateFormat非线程安全处理

  类SimpleDateFonnat主要负责日期的转换与格式化,但在多线程的环境中,使用此类容易造成数据转换及处理的不准确,因为SimpleDateFormat类并不是线程安全的。

1、出现异常
  本示例将实现使用类SimpleDateFormat在多线程环境下处理日期但得出的结果却是错误的情况,这也是在多线程环境开发中容易遇到的间题。

public class MyThread extends Thread {
private SimpleDateFormat sdf;
private String dateString;

public MyThread(SimpleDateFormat sdf, String dateString) {
super();
this.sdf = sdf;
this.dateString = dateString;
}

@Override
public void run() {
try {
Date dateRef = sdf.parse(dateString);
String newDateString = sdf.format(dateRef).toString();
if (!newDateString.equals(dateString)) {
System.out.println("ThreadName=" + this.getName()
+"报错了,日期字符串:" +dateString
+",转换成的日期为:"+newDateString);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String[] dateStringArray = new String[]{"2001-01-01","2001-01-02","2001-01-03",
"2001-01-04","2001-01-05","2001-01-06","2001-01-07","2001-01-08"};
MyThread[] threadArray = new MyThread[10];
for (int i=0; i<8; i++) {
threadArray[i] = new MyThread(sdf, dateStringArray[i]);
}
for (int i=0; i<8; i++) {
threadArray[i].start();
}
}
}

ThreadName=Thread-2报错了,日期字符串:2001-01-03,转换成的日期为:2001-01-01
ThreadName=Thread-3报错了,日期字符串:2001-01-04,转换成的日期为:2199-12-02
ThreadName=Thread-1报错了,日期字符串:2001-01-02,转换成的日期为:2199-12-02
ThreadName=Thread-7报错了,日期字符串:2001-01-08,转换成的日期为:2001-08-06
ThreadName=Thread-5报错了,日期字符串:2001-01-06,转换成的日期为:2001-08-06
  从控制台中打印的结果来看,使用单例的SimpleDateFormat类在多线程的环境中处理日期,极易出现日期转换错误的情况。
  
2、解决异常1:创建了多个类的实例

public class DateTools {
//将字符串类型的日期dateString按照formatPattern转成相应的Date类型
public static Date parse(String formatPattern, String dateString)
throws ParseException {
return new SimpleDateFormat(formatPattern).parse(dateString);
}

public static String format(String formatPattern, Date date) {
return new SimpleDateFormat(formatPattern).format(date);
}
}

将MyThread类的run方法修改为:

    @Override
public void run() {
try {
//Date dateRef = sdf.parse(dateString);修改为下面的代码
Date dateRef = DateTools.parse("yyyy-MM-dd", dateString);

//String newDateString = sdf.format(dateRef).toString();修改如下
String newDateString = DateTools.format("yyyy-MM-dd",dateRef);
if (!newDateString.equals(dateString)) {
System.out.println("ThreadName=" + this.getName()
+"报错了,日期字符串:" +dateString
+",转换成的日期为:"+newDateString);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
控制台中没有输出任何异常,解决处理错误的原理其实就是创建了多个类的实例。

3、解决异常方法2:使用ThreadLocal类
  前面介绍过,ThreadLocal类能使线程绑定到指定的对象。使用该类也可以解决多线程环境下SimpleDateFormat类处理错误的情况。
DateTools修改为如下:

public class DateTools {
private static ThreadLocal<SimpleDateFormat> t1 = new ThreadLocal<SimpleDateFormat>();

public static SimpleDateFormat getSimpleDateFormat(String datePattern) {
SimpleDateFormat sdf = null;
sdf = t1.get();
if (sdf == null) {
sdf = new SimpleDateFormat(datePattern);
t1.set(sdf);
}
return sdf;
}
}

MyThread类里的run方法修改为如下:

    @Override
public void run() {
try {
//Date dateRef = sdf.parse(dateString);修改为下面的代码
//Date dateRef = DateTools.parse("yyyy-MM-dd", dateString);
Date dateRef = DateTools.getSimpleDateFormat("yyyy-MM-dd").parse(dateString);

//String newDateString = sdf.format(dateRef).toString();修改如下
//String newDateString = DateTools.format("yyyy-MM-dd",dateRef);
String newDateString = DateTools.getSimpleDateFormat("yyyy-MM-dd").format(dateRef);
if (!newDateString.equals(dateString)) {
System.out.println("ThreadName=" + this.getName()
+"报错了,日期字符串:" +dateString
+",转换成的日期为:"+newDateString);
}
} catch (ParseException e) {
e.printStackTrace();
}
}

控制台没有错误信息输出。