1.先写两个synchronized方法,实现交替打印数组和字母.并写出主方法调用后面的线程
public class Work1A {
boolean b = false;
public synchronized void show1() throws InterruptedException {
for(int i=1;i<=52;i++) {
if (b==true) {
wait();
}
System.out.print(i);
i++;
System.out.print(i);
b=true;
notifyAll();
}
}
public synchronized void showA() throws InterruptedException {
for(int i=65;i<=90;i++) {
if(b==false) {
wait();
}
System.out.print((char)i);
b=false;
notifyAll();
}
}
public static void main(String[] args) {
Work1A w1 = new Work1A();
Test1 t1 = new Test1(w1);
TestA t2 = new TestA(w1);
t1.start();
t2.start();
}
}
2.在写两个线程类来执行上面两个打印方法,并在上面调用
public class Test1 extends Thread{
private Work1A w1;
public Test1(Work1A w1) {
this.w1 = w1;
}
@Override
public void run() {
try {
w1.show1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class TestA extends Thread{
private Work1A w1;
public TestA(Work1A w1) {
this.w1 = w1;
}
@Override
public void run() {
try {
w1.showA();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
希望文章可以帮助大家,一起进步,奥力给!