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,因此会进入无限循环

Thread.sleep是否会刷新工作内存_第1张图片

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

Thread.sleep是否会刷新工作内存_第2张图片

你可能感兴趣的:(多线程)