某公司春招笔试题:Java多线程--三个线程分别按顺序输出a、b、c。要求循环输出十次。
可惜没提交....放代码记录一下
public class Main {
static int count = 0;
static final Object obj = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
//打印十次之后打印
if(count>28) break;
synchronized (obj) {
if (count % 3 == 0) {
System.out.println("a");
count++;
obj.notifyAll();
} else
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (obj) {
if (count % 3 == 1) {
System.out.println("b");
count++;
obj.notifyAll();
} else
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (obj) {
if (count % 3 == 2) {
System.out.println("c");
count++;
obj.notifyAll();
} else
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
public void runAll() {
t1.start();
t2.start();
t3.start();
}
public static void main(String[] args) {
Main t = new Main();
t.runAll();
}
}