天天看点

2020/11/03java作业八

2020/11/03java作业八

1.当一个共享变量被volatile修饰时,它会保证修改的值会立即被更新到主存,当有其他线程需要读取时,它会去内存中读取新值,而普通的共享变量不能保证可见性,因为普通共享变量被修改之后,什么时候被写入主存是不确定的,当其他线程去读取时,此时内存中可能还是原来的旧值。

2.

2020/11/03java作业八
package a;
class T1 implements Runnable{
	public void run(){
        System.out.println("洗水壶");
        try{
            Thread.sleep(200); 
        }catch(InterruptedException e) {}
    }
}

class T2 implements Runnable{
	public void run(){
        for(int i=1;i<16;i++){
            System.out.println("第"+i+"分钟烧水");
            try{
                Thread.sleep(200); 
            }catch(InterruptedException e) {}
        }
    }	
}
class T3 implements Runnable{
	public void run() {
		System.out.println("泡茶");
		try{
			Thread.sleep(200);
		}catch(InterruptedException e) {}
	}
	
}

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

class T5 implements Runnable{
	public void run(){
        for(int i=1;i<3;i++){
            System.out.println("第"+i+"分钟洗茶杯");
            try{
                Thread.sleep(200); 
            }catch(InterruptedException e) {}
        }
    }
	
}

class T6 implements Runnable{
	public void run(){
        System.out.println("拿茶叶");
        try{
            Thread.sleep(200); 
        }catch(InterruptedException e) {}
    }
	
}

public class qw{
	public static void main(String[]args) {
	T1 aa=new T1();
	T2 bb=new T2();
	T3 cc=new T3();
	T4 dd=new T4();
	T5 ee=new T5();
	T6 ff=new T6();
	Thread t1=new Thread (aa);
	Thread t2=new Thread (bb);
	Thread t3=new Thread (cc);
	Thread t4=new Thread (dd);
	Thread t5=new Thread (ee);
	Thread t6=new Thread (ff);
	t1.start();
	try {
        t1.join();
    } 
	catch (InterruptedException e) {}	
	t2.start();
	t4.start();
    try {
        t4.join();
    } catch (InterruptedException e) {}
    t5.start();
    try {
        t5.join();
    } catch (InterruptedException e) {}
    t6.start();
    try {
        t6.join();
    } catch (InterruptedException e) {}
	try {
        t2.join();
    } catch (InterruptedException e) {}
	t3.start();
}
}
           

结果:

2020/11/03java作业八