我目前正在研究线程和同步。我试图用这个程序打印“A”2次,“B”1次,“C”打印4次,这基本上是有效的,但我想知道是否有一个更小,更简单的解决方案,比如将所有类放入一个或类似的东西中。
下面是代码。
public class foo {
public static int countA = 0;
public static int countB = 0;
public static int countC = 0;
public static void main(String[] args) {
AThread athread = new AThread(new AClass());
BThread bthread = new BThread(new BClass());
CThread cthread = new CThread(new CClass());
athread.start();
bthread.start();
cthread.start();
}
static class AClass {
public synchronized void printA() throws InterruptedException {
if(countA == 2)
wait();
for(int i=1; i<3; i++) {
System.out.println("A"+i);
countA++;
}
}
}
static class BClass{
public synchronized void printB() throws InterruptedException {
if(countB == 1)
wait();
for(int i=1; i<2; i++) {
System.out.println("B"+i);
countB++;
}
}
}
static class CClass{
public synchronized void printC() throws InterruptedException {
if(countC == 4)
wait();
for(int i=1; i<5; i++) {
System.out.println("C"+i);
countC++;
}
}
}
static class AThread extends Thread {
AClass A = new AClass();
AThread(AClass a){
this.A = a;
}
public void run() {
try {
A.printA();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class BThread extends Thread {
BClass B = new BClass();
BThread(BClass b){
this.B = b;
}
public void run() {
try {
B.printB();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class CThread extends Thread {
CClass C = new CClass();
CThread(CClass c){
this.C = c;
}
慕田峪7331174
长风秋雁
相关分类