Two Methods of Cross Printing for Java Multithreaded Actual Warfare
- 2021-06-29 10:53:29
- OfStack
Required results: Print "printA..." five times and then "printB..." five times, one second interval for each print, 20 repetitions
Mode 1: Use the wait () and notifyAll () methods
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();
}
}
}
Mode 2: Use the await () and signalAll () methods
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();
}
}
}
summary