多线程简单通信问题:
(一道题解决简单交叉通信问题)
题目:要求两个线程,同时打印字母,每个线程都能连续打印3个字母。并且连续打印3个小写字母后,换成打印3个大写字母,再换成打印3个小写字母,以此类推。当字母循环到z之后,回到a。
(注:Char("65") A,Char("97") a 连续;例如:Char("65") A,Char("66") B)
效果如图:
代码处:
public class MyThread implements Runnable {
private char letter = 'a'; //'a'是97,'A'是65;
private boolean flag = true;//交叉的通信利用一个boolean属性来判断;
@Override
public void run() {
while (true) {
synchronized (this) {
this.notify();//唤醒被wait的线程;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}//使程序运行更有节奏;
//把循环放在判断语句外,能够更有效的处理多次打印问题(内部判断);
for (int i = 0; i < 3; i++) {
if (letter > 'z') {
letter = 'a';
}
if (flag) {
System.out.println(Thread.currentThread().getName() +
"->" + (letter++));//打印小写字母;本身就是char型;
} else {
System.out.println(Thread.currentThread().getName() +
"->" + (char) (letter++ - 32));//打印大写字母;
}
}
flag=!flag;//根据flag判断下一次执行哪一块的内容;(一定要放在wait的前面,保
证能够使得下一次的程序的运行时候能够运行不一样的if语句中的内容;)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}//交出锁,进入暂停;
}
}
}
}
class test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread one = new Thread(myThread);
Thread two = new Thread(myThread);
one.start();
two.start();
}
}