您的位置:首页 > 职场人生

java常见面试题3:线程间通信

2013-11-23 14:23 471 查看
写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。

打印顺序为12A34B56C78D……5152Z。要求用线程间的通信。

代码清单:

class Printer {
private int index = 1;
  /* 打印数字*/
public synchronized void print(int i) {
while (index % 3 == 0) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print(i);
index++;
notifyAll();
}

  /* 打印字母*/
public synchronized void print(char c) {
while (index % 3 != 0) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print(c);
index++;
notifyAll();
}
}

class NOPrinter implements Runnable {
private Printer p;

NOPrinter(Printer p) {
this.p = p;
}

public void run() {
for (int i = 1; i <= 52; i++) {
p.print(i);
}
}
}

class LetterPrinter implements Runnable {
private Printer p;

LetterPrinter(Printer p) {
this.p = p;
}

public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
p.print(c);
}
}
}

public class ResourceDemo {
public static void main(String[] args) {
Printer p = new Printer();
NOPrinter np = new NOPrinter(p);
LetterPrinter lp = new LetterPrinter(p);

Thread th1 = new Thread(np);
Thread th2 = new Thread(lp);
th1.start();
th2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: