java多线程--给点1,2,A,B四个线程,交叉输出数字和字母

输出例子:1A2B,1B2A,2B1A,2A1B,A1B2等


package observer;



public class threadtest {

private static boolean flag1,flag2,flagA,flagB;//判断哪个字符用过

private static int state = 1; //1是数字,2是字母
private static String result = "";


public synchronized void printNum(char i){
if(result.equals("")){ //如果是第一个字符,直接加进去
state = 2;
result += i;
if(i == '1')
flag1 = true;
else if(i == '2')
flag2 = true;
return;
}
while(state == 2){ //字母状态,则线程进入等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

result += i == '1' ? '1':'2';
state = 2;
if(i == '1')
flag1 = true;
else if(i == '2')
flag2 = true;
//唤醒所有等待该方法执行结束的线程执行该方法
notifyAll();
}
public synchronized void printChar(char i){

if(result.equals("")){
state = 1;
result += i;
if(i == 'A')
flagA = true;
else if(i == 'B')
flagB = true;
return;
}

while(state == 1){ //字符状态,则线程进入等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

result += i == 'A' ? 'A':'B';
state = 1;
if(i == 'A')
flagA = true;
else if(i == 'B')
flagB = true;
notifyAll();
}


class A extends Thread{
private threadtest print;
public A(threadtest print){
this.print = print;
}
public void run(){
this.print.printChar('A');
}
}

class B extends Thread{
private threadtest print;
public B(threadtest print){
this.print = print;
}
public void run(){
this.print.printChar('B');

}
}



class one extends Thread{
private threadtest print;
public one(threadtest print){
this.print = print;
}
public void run(){
this.print.printNum('1');
}
}

class two extends Thread{
private threadtest print;
public two(threadtest print){
this.print = print;
}
public void run(){
this.print.printNum('2');
}
}



public static void main(String[] args){
threadtest p=new threadtest();
int count = 0;
 for(int i = 0;i < 70;i++){
 Thread t1=p.new one(p);
 Thread t2=p.new two(p);
 Thread t3=p.new A(p);
 Thread t4=p.new B(p);
 t1.start();
 t2.start();
 t3.start();
 t4.start();
 
 while(result.length() < 4)
 ;
 System.out.print(result + "\t");
 count++;
 if(i % 5 == 0)
 System.out.println(count);
 flag1 = false;flag2 = false;flagA = false;flagB = false;

 state = 1; //1是数字,2是字母
 result = "";
 }
 System.out.println(count);
 
   }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值