A classic interview topic: Two threads, print AB Separately, where thread a prints a, thread B prints B, each printing 10 times, making it appear ababababa. Effect
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 () {A for (int i=0;i<10;i++) {business.print_a ();
}}). Start ();
New Thread (New Runnable () {public void run () {A for (int i=0;i<10;i++) {business.print_b ();
}}). Start ();
The 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 3 threads or n threads of the program, the example given below is 3 threads, printing a,b,c 10 times, make it appear abcabc. Effect
public class Threadabc {/** * @param args */public static void main (string[] args) {Final Print bu
siness = new Print ();
New Thread (New Runnable () {public void run () {A for (int i=0;i<100;i++) {business.print_a ();
}}). Start ();
New Thread (New Runnable () {public void run () {A for (int i=0;i<100;i++) {business.print_b ();
}}). Start ();
New Thread (New Runnable () {public void run () {A for (int i=0;i<100;i++) {business.print_c ();
}}). Start ();
The 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 ();
}
}
The
demonstrates once again the importance of software engineering; in multithreaded programs, it should be said that in a program, we should put those business logic code into the same class, so that it's high cohesion, low coupling