Thread.sleep是否会刷新工作内存

工厂类

public class ProductFactory {
	
	public Future createProduct(String name) {
		Future f = new Future(); 
		System.out.println("开始处理订单");
		Thread thread = new Thread(new MyThread(f,name));
		thread.start();
		return f;
	}

}

产品类

public class Product {

	private int id;
	private String name;

	...
    ..
    .

	public Product(int id, String name) {
		System.out.println("开始生产 " + name);
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		this.id = id;
		this.name = name;
		System.out.println(name + "生产完毕");
	}

}

生产产品线程类

public class MyThread implements Runnable{
	Future f;
	String name;
	
	public MyThread(Future f,String name){
		this.f=f;
		this.name = name;
	}
	
	@Override
	public void run() {
		Product p = new Product(new Random().nextInt(), name);
		f.setProduct(p);
	}
}

订单类

public class Future {
	
	private  Product product;
	
	
	public void setProduct (Product product) {
		this.product = product;
	}
	
	public Product get () throws InterruptedException {
		while(product==null){
//			Thread.sleep(0);
		}
		return product;
	}

}

测试类

public class Demo {
	
	public static void main(String[] args) throws InterruptedException {
		
		ProductFactory pf = new ProductFactory();
		
		System.out.println("下订单");
		Future f = pf.createProduct("蛋糕");
		
		System.out.println("我去上班了....");
		
		System.out.println("下班了,我去取" + f.get());
	}

}

结论及猜想

若订单类get()方法中的while循环中不进行Thread.sleep,由于prodcut获取的是工作缓存中的值为null,因此会进入无限循环

若订单类get()方法中的while循环中进行Thread.sleep,由会刷新工作内存,循环能正常退出

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值