There are three thread IDs are a, B, C, please have a multi-line programming implementation, on-screen cycle of printing 10 times abcabc ...
Due to the uncertainty of thread execution, it is necessary to control multi-threaded synchronization to ensure such an orderly output.
There are two basic methods of thread synchronization:
(1) Synchronized
(2) Wait,notify,notifyall
Now the two methods are used to solve the problem.
public class Demo01 {
public static void Main (string[] args) {
Startlock lock = new Startlock ();
New Thread (New Method1 ("a", lock), "thread One"). Start ();
New Thread (New Method1 ("B", Lock), "thread Two"). Start ();
New Thread (New Method1 ("C", Lock), "thread Three"). Start ();
}
}
Class Method1 implements Runnable {
Private String name = "";
Private Startlock lock = null;
private int count=10;
Public Method1 (String name, Startlock Lock) {
THIS.name = name;
This.lock = lock;
}
@Override
public void Run () {
while (count>0) {
Synchronized (lock) {
if (Lock.getname (). Equalsignorecase (THIS.name)) {
System.out.print ("Current thread Name:" +thread.currentthread (). GetName () + "+name+" ");
if (name = = "C") {
System.out.println ();
}
count--;
if (This.name.equals ("A")) {
Lock.setname ("B");
} else if (This.name.equals ("B")) {
Lock.setname ("C");
} else if (This.name.equals ("C")) {
Lock.setname ("A");
}
}
}
}
}
}
Class Startlock {
Public String name = "A";
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}
//------------------------------------------------------------------------------------------------------------- ---------------------
Method (ii) The thread class is modified as follows, as in other classes:
Class Method2 implements Runnable {
Private String name = "";
Private Startlock lock = null;
private int count=10;
Public Method2 (String name, Startlock Lock) {
THIS.name = name;
This.lock = lock;
}
@Override
Public void Run () {
while (count>0) {
Synchronized (lock) {
while (!lock.getname (). Equalsignorecase (THIS.name)) {
try{
Lock.wait ();
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
System.out.print (name);
count--;
if (This.name.equals ("A")) {
Lock.setname ("B");
} else if (This.name.equals ("B")) {
Lock.setname ("C");
} else if (This.name.equals ("C")) {
Lock.setname ("A");
}
Lock.notifyall ();
}
}
}
}
Java multi-threaded face question