写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。 打印顺序为12A34B56C78D„„5152Z。要求用线程间的通信。
- public class ThreadTest {
- public static void main(String[] args) {
-
- Flag flag = new Flag();
-
- printNum printNum = new printNum(flag);
- printLet printLet = new printLet(flag);
-
- Thread t1 = new Thread(printNum);
- Thread t2 = new Thread(printLet);
-
- t1.start();
- t2.start();
-
- }
- }
- class Flag{
- private boolean flag;
- public void setTrue(){
- flag=true;
- }
- public void setFalse() {
- flag=false;
- }
- public boolean getFlag() {
- return flag;
- }
- }
- class printNum implements Runnable{
- private Flag f;
- public printNum(Flag f) {
- super();
- this.f = f;
- }
- public void run() {
- synchronized (f) {
-
- for (int i = 1; i <= 52; i+=2) {
-
- if(f.getFlag())
- try{f.wait();}catch (InterruptedException e) {}
-
- System.out.print(i+""+(i+1));
-
- f.setTrue();
-
- f.notify();
- }
- }
- }
- }
- class printLet implements Runnable{
- private Flag f;
-
- public printLet(Flag f) {
- super();
- this.f = f;
- }
- @Override
- public void run() {
- synchronized (f) {
-
- for (int i = 0; i < 26; i++) {
-
- if(!f.getFlag())
- try{f.wait();}catch (InterruptedException e) {}
-
- System.out.print((char)('A'+i));
-
- f.setFalse();
-
- f.notify();
- }
- }
- }
- }
复制代码
|
|