public class myservice {
private volatile boolean flag = false;
public synchronized void printa() {
try {
while (flag) {
wait();
}
for (int i = 0; i < 5; i++) {
system.out.println("printa...");
timeunit.seconds.sleep(1);
}
flag = true;
notifyall();
} catch (interruptedexception e) {
e.printstacktrace();
}
}
public synchronized void printb() {
try {
while (!flag) {
wait();
}
for (int i = 0; i < 5; i++) {
system.out.println("printb...");
timeunit.seconds.sleep(1);
}
flag = false;
notifyall();
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
public class backupa implements runnable {
private myservice myservice;
public backupa(myservice myservice) {
super();
this.myservice = myservice;
}
@override
public void run() {
myservice.printa();
}
}
public class backupb implements runnable {
private myservice myservice;
public backupb(myservice myservice) {
super();
this.myservice = myservice;
}
@override
public void run() {
myservice.printb();
}
}
public class run {
public static void main(string[] args) {
myservice myservice = new myservice();
for (int i = 0; i < 20; i++) {
new thread(new backupa(myservice)).start();
new thread(new backupb(myservice)).start();
}
}
}
方式二:使用await()和signalall()方法
public class myservice {
private lock lock = new reentrantlock();
private condition condition = lock.newcondition();
private boolean flag = false;
public void printa() {
try {
lock.lock();
while (flag) {
condition.await();
}
for (int i = 0; i < 5; i++) {
system.out.println("printa...");
timeunit.seconds.sleep(1);
}
flag = true;
condition.signalall();
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
lock.unlock();
}
}
public void printb() {
try {
lock.lock();
while (!flag) {
condition.await();
}
for (int i = 0; i < 5; i++) {
system.out.println("printb...");
timeunit.seconds.sleep(1);
}
flag = false;
condition.signalall();
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
lock.unlock();
}
}
}
public class threada implements runnable {
private myservice myservice;
public threada(myservice myservice) {
super();
this.myservice = myservice;
}
@override
public void run() {
myservice.printa();
}
}
public class threadb implements runnable {
private myservice myservice;
public threadb(myservice myservice) {
super();
this.myservice = myservice;
}
@override
public void run() {
myservice.printb();
}
}
public class run {
public static void main(string[] args) {
myservice myservice = new myservice();
for (int i = 0; i < 20; i++) {
new thread(new threada(myservice)).start();
new thread(new threadb(myservice)).start();
}
}
}