1 .
需求:
*自己写一个标志位
* flag = true 打印了数字了还没打印字母, 此时 应该 让数字等着 打印 字母
* false 打印了字母了 还没打印数字,此时 应让 字母等着, 打印数字
package com.qf.demo3;
/**
* 需求:
* A12B34C56......Z5152
*
* 两个线程
* 一个字母
* 一个数字
*
*用到 线程间通信
*
*wait
*notify
*
*
*money ==1000 == 0
*
*自己写一个标志位
* flag = true 打印了数字了还没打印字母, 此时 应该 让数字等着 打印 字母
* false 打印了字母了 还没打印数字,此时 应让 字母等着, 打印数字
*
*/
public class Test3 {
public static void main(String[] args) {
Resurce resurce = new Resurce();
Number number = new Number(resurce);
Letter letter = new Letter(resurce);
Thread thread = new Thread(number);
Thread thread2 = new Thread(letter);
thread.start();
thread2.start();
}
}
//true 打印了数字 还没打印字母
// false 打印了 字母还没有打印数字
class Resurce {
boolean flag = true; //true 打印了数字 还没打印字母
// false 打印了 字母还没有打印数字
public synchronized void printNumber(int num){
// 1判断是否应该wait
if(flag == true){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 如果没有进入wait 目前来说是false 应该打印数字
System.out.print(num+""+(num+1));//
//改变状态
flag = true;
this.notify();
}
public synchronized void printLetter(int letter){
if(flag == false){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 如果没有进入 wait 证明现在是true ,应该打印字母
System.out.print((char)letter);
// 已经打印过了字母了. 应该吧状态改变成为false
flag = false;
this.notify();
}
}
class Number implements Runnable{
Resurce resurce;
public Number(Resurce resurce) {
this.resurce = resurce;
}
public void run() {
for (int i = 1; i <= 52; i+=2) {
resurce.printNumber(i);
}
}
}
class Letter implements Runnable{
Resurce resurce;
public Letter(Resurce resurce) {
this.resurce = resurce;
}
public void run() {
for (int i = 0; i < 26; i++) {
resurce.printLetter(65+i);
}
}
}