java生产者消费者
题目:请用多线程实现一个生产者类和一个消费者类,生产者随机生成20个字符,消费者将字符打印到控制台。
class SyncStack{ //同步堆栈类
private int index = 0; //堆栈指针初始值为0
private char []buffer = new char[6]; //堆栈有6个字符的空间
public synchronized void push(char c){ //加上互斥锁
while(index = = buffer.length){ //堆栈已满,不能压栈
try{
this.wait(); //等待,直到有数据出栈
}catch(InterruptedException e){}
}
this.notify(); //通知其它线程把数据出栈
buffer[index] = c; //数据入栈
index++; //指针向上移动
}
public synchronized char pop(){ //加上互斥锁
while(index ==0){ //堆栈无数据,不能出栈
try{
this.wait(); //等待其它线程把数据入栈
}catch(InterruptedException e){}
}
this.notify(); //通知其它线程入栈
index- -; //指针向下移动
return buffer[index]; //数据出栈
}
}
class Producer implements Runnable{ //生产者类
SyncStack theStack;
//生产者类生成的字母都保存到同步堆栈中
public Producer(SyncStack s){
theStack = s;
}
public void run(){
char c;
for(int i=0; i<20; i++){
c =(char)(Math.random()*26+'A');
//随机产生20个字符
theStack.push(c); //把字符入栈
System.out.println("Produced: "+c); //打印字符
try{
Thread.sleep((int)(Math.random()*1000));
/*每产生一个字符线程就睡眠*/
}catch(InterruptedException e){}
}
}
}
相关文档:
SCJP5学习笔记
要理解线程调度的原理,以及线程执行过程,必须理解线程栈模型。
线程栈是指某时刻时内存中线程调度的栈信息,当前调用的方法总是位于栈顶。线程栈的内容是随着程序的运行动态变化的,因此研究线程栈必须选择一个运行的时刻(实际上指代码运行到什么地方)。
下面通过一个示例性的 ......
inkfish原创,请勿商业性质转载,转载请注明来源(http://blog.csdn.net/inkfish)。
这里忽略了jar,因为jar实质上属于zip压缩。(来源:http://blog.csdn.net/inkfish)
JDK ZLIB压缩:(来源:http://blog.csdn.net/inkfish)
package study.inkfish.compress;
import java.io.BufferedInputStream;
import ......
java是一种面向对象的编程语言,怎么理解?
java写的程序都是面向对象的吗?
你可能认为,java生来就是面向对象的。
且看:
package cn.nileader.calculate_OPP;
import java.util.Scanner;
/**
* 这是一个OPP的的计算器(加法和减法)
* @author nileader
* @see http://www.nileader.cn
*/
public cla ......
1.使用java.util.Properties类的load()方法
InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2.使用java.util.ResourceBundle类的getBundle()方法
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault ......