使用多執行緒實現輸出1-a 2-b 3-c 4-d ..........

starkbl發表於2021-09-09

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 {

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();

    }

}

}

原文連結:http://www.apkbus.com/blog-813041-61024.html

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/3705/viewspace-2815069/,如需轉載,請註明出處,否則將追究法律責任。

相關文章