您的位置:首页 > 编程语言 > Java开发

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

2015-11-22 21:37 423 查看
输出例子: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);
 
   }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: