Java作业9

1.volatile关键字有什么作用?
由于非volatile变量进行读写的时候,每个线程先从主内存拷贝到CPU缓存中,每个线程可能在不同的CPU上被处理,当一个线程修改了这个变量的值,新值对于其他线程有可能不会立即得知。volatile关键字可以禁用CPU缓存,避免了此类问题。
2.编写Java程序模拟烧水泡茶最优工序。

package thread;

class Thread1 implements Runnable{
    public void run(){
        System.out.println("洗水壶");
        try {
            Thread.sleep(1000); 
        } catch (InterruptedException e) {} 
    }
}

class Thread2 implements Runnable{
    public void run(){
        for(int i=2;i<=4;i++){
        	if(i==2)
                System.out.println("第"+i+"秒洗茶壶");
        	if(i==3)
        		System.out.println("第"+i+"秒洗茶杯");
        	if(i==4)
        		System.out.println("第"+i+"秒拿茶叶");
        	}
            try {
            	Thread.sleep(1000); 
            } catch (InterruptedException e) {} 
        }
    }

class Thread3 implements Runnable{
    public void run(){
    	for(int i=1;i<16;i++) {
    		System.out.println("第"+i+"秒烧水");
    	}
        try {
            Thread.sleep(1000); 
        } catch (InterruptedException e) {} 
    }
}
class Thread4 implements Runnable{
    public void run(){
        System.out.println("泡茶");
        try {
            Thread.sleep(1000); 
        } catch (InterruptedException e) {} 
    }
}
public class test9{
	 public static void main(String[] args) {
		 Thread1 tt1=new Thread1();
		 Thread2 tt2=new Thread2();
		 Thread3 tt3=new Thread3();
		 Thread4 tt4=new Thread4();
	     Thread t1=new Thread (tt1);
	     Thread t2=new Thread (tt2);
	     Thread t3=new Thread (tt3);
	     Thread t4=new Thread (tt4);
	     t1.start();
	     try {
	            t1.join();
	        } catch (InterruptedException e) {}
	     t3.start();
	     t2.start();  
	     try {
	            t2.join();
	        } 
	     catch (InterruptedException e) {}
	    
	    try {
            t3.join();
        } 
	    catch (InterruptedException e) {}
        t4.start();
 }
 
}

在这里插入图片描述

3. 编写一个基于多线程的生产者/消费者Java应用,各产生10个生产者和消费者线程,共享一个缓冲区队列(长度自设),生产者线程将产品放入到缓冲区,消费者线程从缓冲区取出产品。(选做)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值