Multithreading
First, the concept of threading
Thread when the program executes the control unit, a process must have more than one thread, multi-threaded concurrent execution can improve the efficiency of the program, play the effect of simultaneous execution!
For example: The computer at the same time to perform QQ, thunder; start multiple threads to download multiple files; window selling tickets
Second, the way to open the thread
two ways to create threads : Extends thread and implements Runnable
(1), inheritance method
A, define the class inheritance thread.
B, the Run method in the replication thread.
Purpose: Store your custom code in the Run method and let the thread run.
C, create an instance object that defines the class. The equivalent of creating a thread.
D, use this object to invoke the thread's Start method. The function of this method is to start the thread and invoke the Run method.
1 public class Demo2 {2 3 public static void main (string[] args) {4 MyThread mt = new MyThread ();
//4, creating a custom class object 5 Mt.start (); 5, turn on thread 6 7 for (int i = 0; i < i++) {8 System.out.println (Thread.CurrentThread (). GetName () + "BB"); 9 }12 class MyThread extends Thread {//1, defining class inheritance Thread13 public void Run () {//2, overriding the Run method for (int i = 0; I < 3000; i++) {//3, the code to be executed, written in the Run method, System.out.println (Thread.CurrentThread (). GetName () + "AAAAAAAAAAAAAAA" }18}
(2), implementation method
A, define the interface that the class implements Runnable.
b, overwrite the Run method in the Runnable interface. The purpose is also to store the code that the thread wants to run in the Run method.
C, the thread object is created through the thread class.
D, passing the subclass object of the Runnable interface as an argument to the construction method of the thread class
1 public static void main (string[] args) {2 MyThread mt = new MyThread (); 4, create the object of the custom Class 3 thread th=new thread (MT); 4 Th.start (); 5, turn on thread 5 6 for (int i = 0; i < i++) {7 System.out.println (Thread.CurrentThread (). GetName () + "BB"); 8 }11 class MyThread implements Runnable {//1, defining class inheritance Thread12 public void Run () {//2, overriding the Run method t i = 0; I < 3000; i++) {//3, the code that will be executed, written in the Run method, System.out.println (Thread.CurrentThread (). GetName () + "AAAAAAAAAAAAAAA" }17}
The difference between the two methods
1, the difference between the use method:
Inheritance method : Inherit thread, because subclasses rewrite the thread () class in the run (), so call Start () directly;
Implementation Method : Implement the Runnable interface, the constructor passed in the Runnable reference, start () call the Run () method is to determine the member variable runnable reference is empty,
It is not a null compile time to see the runnable run (), the runtime executes the subclass of the Run ();
general use of the implementation method: Although the code is more complex, but avoids the disadvantages of single inheritance, can be more realized,
2, a number of threads of the state (Grandpa Bishop here seems wrong, see other information obtained)
In Java, threads typically have five states of creation, readiness, operation, blocking, and death.
The first is the creation state. In the build thread object, there is no call to the object's Start method, which is the thread in the created state.
The second is the ready state. When the start method of the thread object is called, the thread enters the ready state, but at this point the thread dispatcher has not set the thread to the current thread and is in a ready state. After a thread is running, it is ready to return from waiting or sleeping.
The third is the running state. The thread dispatcher sets the thread in the ready state to the current thread, and the thread enters the running state and starts running the code in the Run function.
The four is the blocking state. A thread is paused when it is running, usually in order to wait for a certain time to occur (for example, a resource is ready) before it continues to run. Methods such as sleep,suspend,wait can cause thread blocking.
Five is the state of death. If a thread's Run method finishes executing or calls the Stop method, the thread dies. For a thread that has died, the start method can no longer be used to get it ready.
3, using anonymous internal classes to implement the thread;
Inherit anonymous inner class method:
1 new Thread () { //1,new class () {} Inherits this class 2 public void Run () { //2, overriding the Run Method 3 for (int i = 0; i <; i++) {
//3, the code that will be executed, written in the Run Method 4 System.out.println ("aaaaaaaaaaaaaaaaaaaaaaaaaaaa" }7}.start ();
Implement anonymous inner class method:
1 new Thread (new Runnable () { //1,new interface () {} Implements this interface 2 public void Run () { //2, overriding the Run Method 3 for (int i = 0; I & Lt 3000; i++) { //3, the code that will be executed, written in the Run Method 4 System.out.println ("BB"
Iv. Synchronization
1. Need to resolve synchronously
A, when multi-threaded concurrency, there are more than one piece of code at the same time, we do not want to be in a section of code execution when the CPU execution change to other threads
b, if two pieces of code are synchronized, then only one period can be executed at the same time, complete execution to execute another thread
Method:
2, synchronous code block method; Keyword: Synchronized add an object to define this piece of code
Multiple synchronous code blocks use the same lock as the object, then these threads synchronize the
Give me a chestnut:
Sell tickets: When multithreaded operations share data, security issues can occur, and we need to synchronize the code of the operational data
1Package TEST; 2 2/* Write three types of ticket, Sealwindow, Ticketsealcenter respectively representative ticket information, ticket window, ticket Center. 3 3 * The ticket office assigns a certain number of tickets, which are sold by a number of ticket offices, using the threading knowledge you have learned to simulate the ticketing process. 4 4 */5 5 6 6 public classTest_1ticket {7 7 8 8 public static voidMain (string[] args) {9 9 Ticket tk = new Ticket ();//Set up ticket information object one by one ticketsealcenter TSC = NE W Ticketsealcenter (TK);//Create a ticket center. Tsc.set (200);//Ticket Center assigns a certain number of tickets to the new Thread (New Sealwindow (TK, "one Window")). Start ();//Create, start Move the thread and start selling tickets. The new Thread (New Sealwindow (TK, "Window No. Second")). Start (); New Thread (New Sealwindow (TK, "Window No. third")). Start (); New Thread (New Sealwindow (TK, "Window No. Fourth")). Start (); 18 18 19 19}20 20}21 classTICKET{22-private static intticket;23 public static intGetTicket () {returnTICKET;25 25}26 public static void Setticket (intTicket) {Ticket.ticket =Ticket;28 28} 29 29}30-ClassTicketsealcenter{33 Ticket Tk=null; 34 34Ticketsealcenter (Ticket tk) {this.tk=TK;36 36}37 Notoginseng, public void set (int t) {//It can set the number of votes 39 39Ticket.setticket (t); 40 40}41 41}42 classSealwindow implements RUNNABLE{44 private String Name=null;Ticket ticket;46 46Sealwindow (Ticket ticket,string name) {this.name=name;48 this.ticket=TICKET;49 49}50 public voidRun () {Wuyi while (true) {52 52Synchronized (ticket) {t= int.Ticket.getticket (); if (t>0) {System.out.println (name+ ":" + (tsex= "+)Sex); Flag=false; 31Notify (); 32} }34//Storage thread input implements runnable{36 private Resource r;37 Input (Resource R {this.r= r;39 }40 @Override41 public void Run () {$ int x=0 ; if (x==0 ) {R.seti Nput ("Zhang San", "Waman" ); }49 x= (x+1)%2;//if and Else cross print } n }52//Fetch Thread-class Output Impleme NTS runnable{54 Private Resource r;55 Output (Resource r) {this.r= r;57 }58 public void ru N () {R.getoutput (true ) { = (); Sourcedemo }62 }63 }64 ublic static void main (string[] args) {Resource r=new Resource ();//operates the same resource, the new Thread (new Input (R)). Start ();// Save the new Thread (new Output (R)). Start ();//Take the }71} span>
1) Wait (), notify (), Notifyall (), is used to manipulate the thread why is it defined in the object class?
A, these methods exist and are synchronized.
B, these methods must be used to identify the synchronized locks that belong to. The same thread that locks wait can only be awakened by the notify of the same lock.
C, a lock can be any object, so the method called by any object must be defined in the object class.
2) What is the difference between wait () and sleep ()?
Wait (): Releases the CPU execution and releases the lock.
Sleep (): Releases the CPU execution and does not release the lock.
3) Why do we need to define notifyall?
Because when you need to wake the other thread. If you use only notify, it is easy to wake up this thread only. Causes the threads in the program to wait.
Three. Communication between threads
- 1. When to communicate
- When multiple threads are executing concurrently, the CPU is randomly switching threads by default
- If we want them to execute regularly, we can use communication, for example, each thread performs a print
- 2. How to Communicate
- Call Wait () to allow the thread to wait for the CPU to be yielded
- Call Notify (), Wake up the waiting thread
- Both methods must be executed in the synchronization code, and the synchronization lock object is used to invoke the
- 3. Issues with multiple thread communication
- The Notify () method is a random wake-up of a thread
- The Notifyall () method is to wake all threads
- JDK5 Unable to wake a specified thread before
- If the communication between multiple threads, you need to use Notifyall () to notify all threads, use while to repeatedly judge the condition
Four. After JDK5, the line program control system
- 1. Synchronization
- Synchronizing using the Lock () and Unlock () Methods of the Reentrantlock class
- 2. Communication
- Use the Newcondition () method of the Reentrantlock class to get the condition object
- Use condition's await () method when you need to wait, wake up with the signal () method
- Different threads use different condition so that you can tell which thread to look for when waking up.
Five. Synchronous and non-synchronous classes
Synchronous security inefficient, unsafe and high efficiency for different steps
StringBuffer StringBuilder
Vector ArrayList
Hashtable HashMap
Dark Horse Programmer--summary--multithreading--Change 12