1.缓冲类
package demo07;
public class Buffer {
private static final int maxCount=1;//最大存储线程数量
private int ch;
private int charnum='a'-1;//字母a-z
private int num=0;//数字1-26
public Buffer(int ch){
this.ch=ch;
}
synchronized public void outNumbers(int ch){
while(this.ch+ch>maxCount){
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.num++;
System.out.print(this.num+"--");
this.ch+=ch;
this.notifyAll();
}
synchronized public void outChars(int ch){
while(this.ch<maxCount){
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.charnum+=1;
System.out.println((char)this.charnum);
this.ch-=ch;
this.notifyAll();
}
}
2.数字输出类
package demo07;
public class Numbers extends Thread{
private Buffer buffer;
private int ch;
public Numbers(Buffer buffer,int ch){
this.buffer=buffer;
this.ch=ch;
}
@Override
public void run() {
this.buffer.outNumbers(ch);
}
}
3.字母输出类
package demo07;
public class CharNumbers extends Thread{
private Buffer buffer;
private int ch;
public CharNumbers(Buffer buffer,int ch){
this.buffer=buffer;
this.ch=ch;
}
@Override
public void run() {
this.buffer.outChars(ch);
}
}
4.测试类
package demo07;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Buffer buffer=new Buffer(0);
for(int i=0;i<26;i++){
Thread num=new Numbers(buffer,1);
Thread charnum=new CharNumbers(buffer,1);
num.start();
charnum.start();
}
}
}