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个生产者和消费者线程,共享一个缓冲区队列(长度自设),生产者线程将产品放入到缓冲区,消费者线程从缓冲区取出产品。(选做)