package thread.threaddemo1;
/**
* 写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……5152Z。要求用线程间的通信。
* @author jiangbin031
*
*/
public class Test {
public static void main(String[] args) {
Printer printer = new Printer();
Thread letter = new LetterPrinter(printer);
Thread number = new NumberPrinter(printer);
letter.start();
number.start();
}
}
package thread.threaddemo1;
/**
* 字母打印线程
* @author jiangbin031
*/
public class LetterPrinter extends Thread{
Printer print;
public LetterPrinter(Printer print){
this.print = print;
}
@Override
public void run() {
for(char i='A';i<='Z';i++){
print.printLetter(i);
}
}
}
package thread.threaddemo1;
/**
* 数字打印线程
* @author jiangbin031
*
*/
public class NumberPrinter extends Thread{
Printer print;
public NumberPrinter(Printer print){
this.print = print;
}
@Override
public void run() {
for(int i=1;i<=52;i++){
print.printNumber(i);
}
}
}
package thread.threaddemo1;
public class Printer {
private int flag = 1;
public synchronized void printNumber(int number){
while(flag%3==0){
try {
wait();
} catch (InterruptedException e) {
}
}
flag++;
System.out.println(number);
notifyAll();
}
public synchronized void printLetter(char letter){
while(flag%3!=0){
try {
wait();
} catch (InterruptedException e) {
}
}
flag++;
System.out.println(letter);
notifyAll();
}
}