Multithreading
When running a Java program, in fact, already it has a thread, and that is the main thread.
All thread object must be an instance of the Thread class or subclass,
-
Subclass definition of the Thread class, the class and override run () method, the method body of the run () method represents the thread needs to complete the task, so the run () method is called thread of execution.
-
Create a Thread subclass instance, the thread object is created
-
Call the thread object's start () method to start the thread
Proceed as follows:
-
Runnable interface implementation class is defined, the interface and override run () method, the method body run () method of the same thread of execution threads.
-
Create an instance of Runnable implementation class and use it to create an instance of the Thread Thread object as a target, the Thread object is the real thread object.
-
Call the thread object's start () method to start a thread.
Example: public class MyRunnable implements Runnable // define the implementation class thread
MyRunnable mr = new MyRunnable (); // create thread objects
Thread t = new Thread (mr) ; // Thread class by way of example, the thread start
t.start ();
Virtually all multi-threaded code is by start () method of the Thread run to run. Therefore, whether to inherit the Thread class or implement
tips: Runnable objects only as target Thread object, Runnable class comprises implement the run () method as the only thread of execution. The actual thread object is still the Thread instance, just this Thread thread is responsible for the implementation of the method of its target's run ().
1, a single inheritance restriction inheritance, the way to achieve more than can be achieved
2, different start-up mode
3. Inheritance: when implementing a shared data may need to be static
Implementation: As long as a Runnable implementation class share the same object can be.
4. Inheritance: When you select this lock may not be used,
Implementation: When you select this lock can be used.
( "! new thread") {the Thread new new
@Override
public void RUN () {
for (int I = 0; I <10; I ++) {
System.out.println (getName () + ": being executed!" + I);
}
}
} .start ();
Daemon thread has a feature that if all non-daemon threads have died, then the daemon thread is automatically killed.
Call setDaemon (true) method can set the specified thread as a daemon thread. It must be set before the thread is started, otherwise it will be reported IllegalThreadStateException exception.
Judge thread safety issues
1, if there are multiple threads
3, these threads when using shared data, whether there is a read write
synchronized (sync lock) {
need code synchronization operations
}
Synchronization lock must be an object
Multiple threads objects must use the same lock . Note: At any time, at most one thread can own synchronization lock, who got into the lock on the block, other threads can only wait outside (BLOCKED).
] [Other modifiers synchronized return type method name (parameter list []) throws Exception List] [{
// the code may produce thread safety issues
}
Lock object can not be selected by our own, it is the default:
(1) Static method: the lock object is the object of the current class Class
(2) non-static way: this
When the "data buffer" full, "producer" need to wait, waiting to be awakened;
When the "data buffer" empty, "consumers" need to wait, waiting to be awakened.
-
-
notify: a notification target thread wait set is selected in the release;
-
notifyAll: All threads on the notification object wait set is released.
After being awakened may not be able to resume execution thread immediately notify, because it had interrupted the place is in sync blocks, but at the moment it no longer holds the lock, so she needs to try again to acquire the lock (likely to face other threads competition), after the success can resume execution in place after the original call wait method.
Summarized as follows:
-
If you can get a lock, the thread becomes RUNNABLE (run) status from WAITING state;
-
Otherwise, the thread from WAITING state and becomes BLOCKED (wait for locks) state
Call wait and notify methods need to pay attention to the details
-
wait and notify methods method must be called by the same lock object. Because: the corresponding lock object can be woken notify the use of threads after the wait method call with a lock object.
-
notify and wait method is a method belonging to the class of Object. Because: lock object can be any object, any object which belongs to the class are inherited Object class.
-
Wait wake-up mechanism to solve the classic "producer-consumer" problem
To solve this problem, we must let the producer thread waits in the buffer is full (wait), pause into the blocked state, wait until the next consumer consumes data in the buffer when the notification (notify) is waiting thread resumes to the ready state, start adding data to the buffer. vice versa
First, the angle of the thread on standing: five kinds
1, New: create a thread object, yet start
2, ready: already started, and can be CPU scheduling
3, run: being scheduled
4, blocking: met: sleep (), wait (), wait (time), the other thread join (), join (time), suspend (), the lock is occupied by other threads, etc.
5, death: run () ends normally encountered an unhandled exception or error, stop ()
New state program can only thread calls start (), and can only be called once, if the thread of the new non-state, as has been started threads or thread has died calling start () will error IllegalThreadStateException exception.
Second, the stand angle of the six kinds of code
Such enumeration defined in the class java.lang.Thread.State
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
1, New NEW: create a thread object, yet start
2, run RUNNABLE: CPU can be scheduled, or is scheduled
3, blocked BLOCKED: wait for the lock
4, wait WAITING: wait (), join () and so there is no set time, etc. must notify (), or stoppered end of the thread to resume
5, there is time to wait TIMED_WAITING: sleep (time), wait (time), join (time) and so have time blocking, so time to recover, or interrupt will be restored
Any thread into the synchronized block, before the synchronization method, you must first obtain a lock on the synchronization of the monitor, so when it will release the lock on the synchronization monitor it?
1, the release operation of the lock
The current thread synchronization method, the synchronization code block execution ends .
The current thread appeared untreated Error or Exception block synchronization code, the synchronization process, resulting in an abnormal end of the current thread.
2, will not release the lock operation
线程执行同步代码块或同步方法时,程序调用Thread.sleep()、Thread.yield()方法暂停当前线程的执行。
线程执行同步代码块时,其他线程调用了该线程的suspend()方法将该线程挂起,该线程不会释放锁(同步监视器)。应尽量避免使用suspend()和resume()这样的过时来控制线程。
3、死锁
不同的线程分别锁住对方需要的同步监视器对象不释放,都在等待对方先放弃时就形成了线程的死锁。一旦出现死锁,整个程序既不会发生异常,也不会给出任何提示,只是所有线程处于阻塞状态,无法继续。