(交替打印ab)
public class CalculatorTest {
static boolean flag = true;
static class Word {
String s;
public Word(String a) {
s = a;
}
public void setS(String a) {
s = a;
}
public String getS() {
return s;
}
}
static Word s = new Word("A");
@Test(timeout=60000)
public void main() throws InterruptedException {
ThreadA threadA = new ThreadA();
ThreadB threadB = new ThreadB();
threadA.start();
threadB.start();
}
static class ThreadA extends Thread {
@Override
public void run() {
synchronized(s){
for(int i=0;i<100;i++){
if(s.getS().equals("A")){
System.out.println("---a--");
s.setS("B");
s.notify();
}else{
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
synchronized (s){
for(int i=0;i<100;i++){
if(s.getS().equals("B")){
System.out.println("---b--");
s.setS("A");
s.notify();
}else{
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}