1、volatile关键字有什么作用?
禁用CPU缓存。即不将变量存入CPU缓存中,而是直接在内存中进行读取,这样多个线程访问同一变量时能够会访问到相同的值。
2、编写Java程序模拟烧水泡茶最优工序。
最优工序流程图如下:
Java代码如下:
class Thread1 implements Runnable {
public void run() {
System.out.println("去洗水壶了");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println("洗完水壶了");
System.out.println("开始烧水");
try{
Thread.sleep(8000);
}catch(InterruptedException e){}
System.out.println("烧好水了");
}
}
class Thread2 implements Runnable{
public void run(){
System.out.println("开始洗茶壶");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println("洗完茶壶了");
System.out.println("开始洗茶杯");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println("洗完茶杯了");
System.out.println("去拿茶叶");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println("茶叶拿来了");
}
}
public class Worker{
public static void main(String[] args){
System.out.println("我想喝茶了!");
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
Thread t = new Thread(t1);
Thread tt = new Thread(t2);
t.start();
tt.start();
try{
t.join();
}catch(InterruptedException it){
it.printStackTrace();
}
try{
tt.join();
}catch(InterruptedException it){
it.printStackTrace();
}
System.out.println("可以泡茶了!");
}
}