Java multithreaded implementation outputs simultaneously
- 2020-05-07 19:37:20
- OfStack
1 classic interview topic: two threads, respectively print AB, in which thread A prints A, thread B prints B, each prints 10 times to make ABABABABA.. The effect of
package com.shangshe.path;
public class ThreadAB {
/**
* @param args
*/
public static void main(String[] args) {
final Print business = new Print();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<10;i++) {
business.print_A();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<10;i++) {
business.print_B();
}
}
}).start();
}
}
class Print {
private boolean flag = true;
public synchronized void print_A () {
while(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("A");
flag = false;
this.notify();
}
public synchronized void print_B () {
while(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("B");
flag = true;
this.notify();
}
}
From the above example, we can design a program with 3 threads or even n threads. The following example is 3 threads. Print A, B and C 10 times to make ABCABC.. The effect of
public class ThreadABC {
/**
* @param args
*/
public static void main(String[] args) {
final Print business = new Print();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<100;i++) {
business.print_A();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<100;i++) {
business.print_B();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<100;i++) {
business.print_C();
}
}
}).start();
}
}
class Print {
private boolean should_a = true;
private boolean should_b = false;
private boolean should_c = false;
public synchronized void print_A () {
while(should_b || should_c) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("A");
should_a = false;
should_b = true;
should_c = false;
this.notifyAll();
}
public synchronized void print_B () {
while(should_a || should_c) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("B");
should_a = false;
should_b = false;
should_c = true;
this.notifyAll();
}
public synchronized void print_C () {
while(should_a || should_b) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("C");
should_a = true;
should_b = false;
should_c = false;
this.notifyAll();
}
}
Again, the importance of software engineering; In multithreaded programs, I should say in programs, we should put that business logic code in the same class, making it highly cohesive and loosely coupled