Java第9章:线程

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("可以泡茶了!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值