The reason for the problem stems from a simple interview: The topic requires the following:
Build three threads, a thread prints 10 times A, a thread prints 10 times b,c thread prints 10 times C, requires the thread to run concurrently, and prints 10 times the ABC.
Before we solve the problem, we should add some basic knowledge:
Startup of runnable and thread threads
The thread's start-up is not simply a call to your run method, but rather a thread scheduler that invokes the Run method of all your threads separately.
Our normal run method will not return if not finished, that is, will continue to execute, so that the following method of the Run method is not possible to execute, but the line thread the Run method is not the same, it only a certain amount of CPU time, after the execution of the other thread, In this way, the CPU time Che cut off, because the speed of the switch is very fast, so we feel that many threads are running at the same time.
You simply call the Run method without the effect, so you have to call the start method of the thread class to start your thread. So you have two ways to start a thread
One is to write a class inherited from the thread class, and then rewrite the inside of the Run method, start the thread with the Start method
The second is to write a class implementation Runnable interface, implement the inside of the Run method, with the new Thread (Runnable target). Start () method to launch
Both of these methods must implement the Run method so that thread manager can invoke your run method when the thread is starting.
the relationship between start () and run ()
Difference
The thread class is defined in the Java.lang package. A class that inherits the thread class to overwrite the run () method in this class can implement multithreaded operations, but only one parent class can inherit from a class, which is the limitation of this method.
Implementing the Runnable interface has the following notable benefits over inheriting the thread class:
(1) Suitable for multiple threads of the same program code to handle the same resource situation, the virtual CPU (thread) and the Code of the program, the data effectively separated, better reflect the object-oriented design ideas.
(2) can avoid limitations due to the single inheritance of Java. We often encounter the case that when we want to put a subclass of a class that has been inherited into a multi-threaded, because a class can not have two parent classes at the same time, so can not inherit the thread class, then this class can only adopt the way of implementing the Runnable interface.
(3) It is advantageous to the robustness of the program, the code can be shared by multiple threads, and the code and data are independent. When multiple threads execute code from an instance of the same class, they are said to share the same code. Multiple threads manipulate the same data, regardless of their code. When shared access is the same object, that is, they share the same data. When a thread is constructed, the required code and data are passed in through an object as a constructor argument, an instance of a class that implements the Runnable interface.
I found in the test that the threads are sequential when they inherit the thread, and when the runnable is implemented, the order is really indeterminate.
wait and notify and sleep
Obj.wait (), and obj.notify () must be used with synchronized (obj), that is, wait, and notify is for the OBJ lock that has been acquired, from a syntactic point of view is obj.wait (), Obj.notify must be in synchronized (OBJ) {...} Within the statement block. Functionally, wait means that the thread is actively releasing the object lock after acquiring the object lock, while this thread sleeps. Until the thread is awakened by another thread calling the object's notify (), it can continue to acquire the object lock and continue execution. The corresponding notify () is the wake-up operation of the object lock. But one thing to note is that after the Notify () call, the object lock is not released immediately, but after the corresponding synchronized () {} statement block executes and the lock is automatically freed, the JVM randomly picks a thread in the Wait () object lock, assigns its object lock, wakes the thread, Continue execution. This provides a synchronous, wake-up operation between threads. Both Thread.Sleep () and object.wait () can pause the current thread and release the CPU control, the main difference being that object.wait () releases the control of the object lock while releasing the CPU.
For the Sleep () method, we first need to know that the method belongs to the thread class. The wait () method is part of the object class.
The sleep () method causes the program to pause execution for the specified time, giving up the CPU to that other thread, but his monitoring state remains, and when the specified time is up, it will automatically resume its running state.
During the call to the sleep () method, the thread does not release the object lock.
When the Wait () method is called, the thread discards the object lock, enters the waiting lock pool waiting for the object, and the thread only enters the object lock pool when the Notify () method is called for this object.
With this knowledge, let's solve the problem.
Anatomy of the topic
From the topic we can get a few points:
1: Thread runs at the same time: but does not require a thread to start
2: Print 10 letters for each thread
3: Alternate printing: means that the print operations of three threads are strictly sequential
Thinking analysis
1: Each thread prints a different letter, operates similarly, can be implemented with a uniform class, and is initialized with no use of its own
2: There is a succession between threads, print a thread print, print b thread to print, then to C, loop
How to ensure the ordering of the execution order between threads is the difficulty of this topic,
Difficult breakthrough
The printed thread should enter a wait state after printing a once, until the thread that prints C is printed once C is re-executed
threads that print B and C are also similar
Simple idea
Defines three object traversal a,b,c, each of which obtains the three objects lock to print the corresponding letter once, and then releases the lock of the other two objects once printed once
Problem
Each thread has to obtain three object locks at the same time to print, the first thread is finished printing, if you just release the lock of the other two objects, then no thread can continue to print;
If all three are released, that means the current thread can continue printing.
So, the idea of locking with three objects seems to be unworkable.
one of the right ideas (there may be other ideas)
Each thread only obtains its own and its own prefix object's lock (for example A's prefix is c,b a), in order to print its own letter, and then release the lock of its own prefix object, into the waiting thread pool of its front-end object, waiting for its prefix object to be awakened before continuing to print
So when does your prefix object wake up?
Very simple idea, print a of the thread after printing a once to enter the pool waiting for the C object, then as long as the print C thread in the printing of their own time to wake up a bit, so that the thread printing a can print C after the thread printed once C can be printed once A;
Once you have printed your own, immediately wake yourself up, then release the lock of your prefix object, into the waiting thread pool of your front-end object, so that your suffix thread can print immediately, loop in turn, the problem seems to have been resolved.
Potential problems
Because each thread has only two locks and waits for only one lock, the boot order of the threads is still required. If the order of initiation is ACB, let us analyze:
Thread A: Start with an AC two lock, print a, wake up a, enter the thread pool waiting for C to be awakened , release AC
Thread B: Start with AB two locks, print B, Wake B, go to the thread pool waiting for a to be awakened , release AB
Thread c: Start getting BC two locks, print C, Wake C, go to the thread pool waiting for B to wake up, release BC
This is completely no problem, so we must ensure that the print ABC corresponds to the thread sequence initiated
It's simple: just sleep a little after starting a, if that's all.
New Thread (Athread). Start (); // Thread.Sleep (ten); New Thread (Bthread). Start (); // Thread.Sleep (ten); New Thread (Cthread). Start (); // Thread.Sleep (ten);
if your class is implements Runnable , the three-thread boot sequence is not guaranteed,
Of course, you can change to extends thread so that the three threads are started sequentially.
The following is the complete implementation code:
/** * * @authorHung Weijie *@versionNovember 20, 2015 morning 10:15:07*/ Public classMythreadprintImplementsrunnable{PrivateString name; PrivateObject prev; PrivateObject Self; Publicmythreadprint (String name,object prev,object self) {//TODO auto-generated Constructor stub This. Name =name; This. prev =prev; This. Self =Self ; } @Override Public voidrun () {//TODO auto-generated Method Stub intCount = 10; while(count>0){ synchronized(prev) {synchronized(self) {System.out.print (name); Count--;//self.notify (); } Try{prev.wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } } Public Static voidMain (string[] args)throwsinterruptedexception{Object a=NewObject (); Object b=NewObject (); Object C=NewObject (); Mythreadprint Athread=NewMythreadprint ("a", C,a); Mythreadprint Bthread=NewMythreadprint ("B", A, b); Mythreadprint Cthread=NewMythreadprint ("C", B,c); NewThread (Athread). Start ();//Thread.Sleep (ten); NewThread (Bthread). Start ();//Thread.Sleep (ten); NewThread (Cthread). Start ();//Thread.Sleep (ten);//Athread.run ();//Bthread.run ();//Cthread.run (); }}
P
Java Multithreading anatomy