The following code is available:
public class TraditionalThreadSynchronized {public static void main(String[] args) {new TraditionalThreadSynchronized().init();}public void init() {final Outputer outputer = new Outputer();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}outputer.out("bbbbbbbbb");}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}outputer.out("aaa");}}}).start();}class Outputer {public synchronized void out(String name) {int len = name.length();for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}public void out1(String name) {int len = name.length();synchronized (Outputer.class) {for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}}}}
Of course, the out and out1 methods can be mutually exclusive,
However, in the following code
public class TraditionalThreadSynchronized {public static void main(String[] args) {new TraditionalThreadSynchronized().init();}public void init() {final Outputer outputer = new Outputer();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}outputer.out("bbbbbbbbb");}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}outputer.out3("aaa");}}}).start();}static class Outputer {public synchronized void out(String name) {int len = name.length();for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}public void out1(String name) {int len = name.length();synchronized (Outputer.class) {for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}}public synchronized static void out3(String name) {int len = name.length();for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}}}
Naturally, when running, the out and out3 methods cannot be mutually exclusive. When thread 1 executes out1 and thread 2 executes out3, the thread can be mutually exclusive,
So how can we make the out and out3 Methods mutually exclusive? It is not applicable to the out1 method?
Please advise