yy's garden

Android什么的

【java线程】两线程交叉打印出12a34b56c....5152z

 

我的网友smith某天研究线程 非要我实现这么个效果 一个线程打印1-52 另一个线程打印a-z 通过synchronized控制两线程交叉输出 1 2 a 3 4 b 5 6 c .... 51 52 z , 于是我非常蛋疼的写下了如下的代码:

 

 
public class Main {
static NumT numT = new NumT();
static CharT charT = new CharT();

static char[] chars = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

public static void main(String[] args) {
synchronized (numT) {
numT.start();
numT.notifyAll();
try {numT.wait();}catch (InterruptedException e){e.printStackTrace();}
charT.start();
}
}

static class NumT extends Thread{
@Override
public void run() {
try {sleep(1000);}catch (InterruptedException e){e.printStackTrace();}
for(int i=0;i<51;){
synchronized (numT) {
System.out.println(++i);
System.out.println(++i);
numT.notifyAll();
try {numT.wait();}catch (InterruptedException e){e.printStackTrace();}
}
}
}
}

static class CharT extends Thread{
@Override
public void run() {
for(int i=0;i<26;i++){
synchronized (numT) {
System.out.println(chars[i]);
numT.notifyAll();
try {numT.wait();}catch (InterruptedException e){e.printStackTrace();}
}
}
}
}
}



posted on 2011-11-25 10:00  tooyond  阅读(1157)  评论(0编辑  收藏  举报

导航