⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cocurrency.java

📁 高质量Java程序设计 源代码
💻 JAVA
字号:
package net.betterjava.design.sideeffect.immunity;
import java.util.Date;

public class Cocurrency extends Thread {
	private Date today;
	private SafeImmunity value;

	public Cocurrency(Date d) {
		today = d;
		value = new SafeImmunity(1, today);
	}

	public void run() {
		//replace Munity with SafeImmunity that uses clone for thread safe		
		try {
			sleep((int) Math.random() * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace(System.out);
		}
		//change reference value take no effect on the date in SafeImmunity
		today.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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -