您的位置:首页 > 其它

写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z。

2013-09-25 19:11 330 查看
写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z。要求用线程间的通信。

注:分别给俩个对象构造一个对象O,数字每打印两个或字母每打印一个就执行O.wait().

package com.lovo.t_9_22;

public class MyThread {

/**
* @param args
*/
public static void main(String[] args) {
Object obj = new Object();
Thread1 th1 = new Thread1(obj);
Thread2 th2 = new Thread2(obj);
th1.start();//开启线程
th2.start();
}

}
/**
* 数字线程类
* @author Administrator
*
*/
class Thread1 extends Thread{
private Object obj;
public Thread1(Object obj){
this.obj=obj;
}
public void run() {
synchronized (obj) {
for(int i=1;i<53;i++){
System.out.print(i);
if(i%2==0){//打印到能被2整除时,需要打印字母,于是需要唤醒其他线程
obj.notifyAll();
try {
obj.wait();//当前对象处于等待状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
}
}

/**
* 字母线程类
* @author Administrator
*
*/
class Thread2 extends Thread{
private Object obj;
public  Thread2(Object obj) {
this.obj=obj;
}
public void run() {
synchronized (obj) {
for(int i=0;i<26;i++){
System.out.print((char)('A'+i)+"");
obj.notifyAll();//打印一个字母就会唤醒其他线程,并当前对象处于等待状态
if(i!=25){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}


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