cocurrency.java

来自「高质量Java程序设计 源代码」· Java 代码 · 共 52 行

JAVA
52
字号
package net.betterjava.design.sideeffect.munity;
import java.util.Date;

public class Cocurrency extends Thread {
	private Date date;
	private Munity value;

	public Cocurrency(Date d) {
		date = d;
		value = new Munity(1, date);
	}

	public void run() {
		try {
			sleep((int) Math.random() * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace(System.out);
		}
		//change reference value also change the date in Munity
		date.setTime(value.nextDate().getTime());
	}

	public Date getDate() {
		return value.getDate();
	}

	public static void main(String[] args) {
		Date today = new Date();
		Cocurrency[] threads = new Cocurrency[6];
		try {
			for (int i = 0; i < threads.length; i++) {
				threads[i] = new Cocurrency(today);
			}

			for (int i = 0; i < threads.length; i++) {
				threads[i].start();
				sleep(10);
				System.out.println(
					"Date in first loop:\n" + threads[i] + threads[i].getDate());
			}

			sleep(1000);
			for (int i = 0; i < threads.length; i++) {
				System.out.println(
					"Date in second loop:\n" + threads[i] + threads[i].getDate());
			}
		} catch (InterruptedException e) {
			e.printStackTrace(System.out);
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?