There is an interview question: Open a child thread and the main thread run at the same time, the child thread output 10 times after the main thread output 100 times, so repeated 50 times. First look at the following code:
Package com.maso.test; /** * * @author Administrator * Two threads, which is a main thread, the first threads run the output 10 times first, the main line then run output 100 times, so repeated 50 times/public class THREADTEST3 Imp
Lements runnable{private static test test;
@Override public void Run () {for (int i=0; i<50; i++) {test.f1 (i);
} public static void Main (string[] args) {test = new test ();
New Thread (New ThreadTest3 ()). Start ();
for (int i=0; i<50; i++) {test.f2 (i); }/** * classifies control and logic and data (which is data) * @author Administrator */Static Class
test{Private Boolean isf1 = true;
/** * Output 10 times/public synchronized void F1 (int j) {if (!ISF1) {
try {this.wait ();
catch (Interruptedexception e) {e.printstacktrace ();
} for (int i=1; i<=10; i++) {System.out.println (Thread.CurrentThread (). GetName
() + "first" + j + "round Patrol, output" + i);
} ISF1 = false;
Notify (); /** * Output 100 times/public synchronized void F2 (int j) {I
F (isf1) {try {this.wait ();
catch (Interruptedexception e) {e.printstacktrace (); for (int i=1; i<=100; i++) {System.out.println (Thread.CurrentThread ().
GetName () + "first" + j + "round Patrol, output" + i);
} ISF1 = true;
Notify (); }
}
}
The above is judged by the IF statement, which does not seem to be a problem, and in practice it is unsafe because the thread may be falsely awakened during the waiting process, so we need to use the while statement. In addition, you need to pay attention to some points when using wait and notify:
1, when you call the object's Wait method and the Notity method, you must first obtain the objects lock (which must be written in synchronized) of object.
2. If the wait method of object is invoked, the thread drops the object lock.
3. If A1, A2, A3 are all in object.wait (), then B calls Object.notify () can only wake one of the A1, A2, A3 (specifically which is determined by the JVM)
4, Object.notifyall () can wake up all.
5, B in Wake up A, b if also hold object lock, then wait until B release lock, a will have the opportunity to execute.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/