1.1 Java multi-threading principles

### 24.01_ multi-threaded (multi-threaded introduced) (understand)
* 1. What is the thread
* A thread is a path of program execution, a process can contain multiple threads
* concurrent execution of multiple threads can improve the efficiency of the program, to complete work on several assignments
* 2. multithreaded application scenarios
* spider simultaneously share to multiple computer screens
* Thunder open multiple threads to download together
* QQ more than one person at the same time and with video
* server to handle multiple client requests

# ## 24.02_ multi-threaded (multi-threaded parallel and concurrent difference) (understand)
* is two parallel tasks run simultaneously, while a is the task, the task B are carried out. (Multicore need the CPU)
* refers to two concurrent tasks to run the request, and the processor can only be subject to a task, put these two tasks, alternating arrangements, due to the short time interval, people feel both tasks in run.
* For example, I chat with two friends, a computer chat with a left-hand operation A, while the right hand chat with another computer B, which is called parallel.
* If you use a computer to give me a message A, B and then immediately give a message, and then talk to A talk, talk talk acetate. This is called concurrency.

### 24.03_ multithreaded (Java Runtime principles and procedures JVM startup is multi-threaded you) (understand)
* A: the Java program works
* Java command to start java virtual machine, start the JVM, equal to start an application , which is the start of a process. The process will start automatically a "main thread", and then the main thread to call the main method of a class.

* B: JVM startup is multi-threaded you
* JVM garbage collection start at least started the thread and the main thread, it is multi-threaded.

### 24.04_ multithreading (way multithreaded program implementation 1) (master)
* 1. inherit the Thread
* defined class inherits the Thread
* override the run method
* to write a new thread to do in the run method
* Create a thread Object
* open a new thread, internal method performed automatically run
*

{class Demo2_Thread public 

/ ** 
 * @param args 
 * / 
  public static void main (String [] args) 
  { 
      the MyThread the MyThread new new MT = (); //. 4, to create a custom class objects 
      mt.start (); // 5, open thread 

      for (int I = 0; I <3000; I ++) 
      { 
          System.out.println ( "BB"); 
      } 
  } 

} 
class the MyThread the extends the thread {//. 1, the definition of class inherits the thread public void RUN () {// 2, override the run method for (int I = 0; I <3000; I ++) {//. 3, the code to be executed, the write process in the run System.out.println ( "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } } }

  

  

 

### 24.05_ multithreading (way multithreaded program implementation 2) (master)
* 2. Implement Runnable
* defining class implements Runnable interface
* implement the run method
* to write a new thread to do in the run method
* Create Self Runnable subclasses object definitions
* create a thread object, passing in the Runnable
* start () call to open a new thread, inside will automatically call the run Runnable () method

{class Demo3_Runnable public 
    / ** 
     * @param args 
     * / 
    public static void main (String [] args) { 
        MyRunnable new new MyRunnable of Mr = (); //. 4, to create a custom class object 
        // Runnable target = new MyRunnable () ; 
        thread T = new new thread (of Mr); //. 5, which is passed as a parameter to the constructor thread 
        t.start (); // 6, open thread 

        for (int i = 0; i <3000; i ++) { 
            System.out.println ( "BB"); 
        } 
    } 
} 

class MyRunnable the implements Runnable {//. 1, a custom class that implements Runnable interface 
    @Override 
    public void run () {// 2, override the run method  
        for (int i = 0; i <3000; i ++) {// 3, the code to be executed, the write process in the run
            System.out. println ( "aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        }
    }

}

  

### 24.06_ multithreading (realization of the principle of Runnable) (understand)
* View source code
* 1, see the Thread class constructor, passing in the Runnable interface references
* 2 () method to find the init target to pass through the member variable the target assignment
* 3 to view the run method, run discovery methods have to judge, if the target is not null will call the run method Runnable interface object subclasses

### 24.07_ multithreading (the difference between the two approaches) (master)
* View source code differences:
* A succession Thread:. As the child class overrides the run Thread class (), when calling start (), direct find run subclass () method
* b implement Runnable:. whether the constructor passing references Runnable, members of variables to remember it, start () call to run () member variables to determine when internal reference method Runnable is empty to see when not empty compile Runnable's run (), the implementation of the runtime is run subclass () method

* inherited Thread
* bonus: you can use the Thread class in a direct, simple code
* drawbacks: if already have a parent class, this method can not be used
* implement Runnable
* bonus: thread class even had their own definition of the parent class does not matter, because the parent class can implement an interface, and the interface is more than achievable
* drawback is: can not use the direct method thread the need to obtain the thread object, the method to get thread, code complexity
### 24.08_ multithreading (anonymous inner classes are two ways to achieve thread) (master)
* Inheritance Thread class

the Thread new new () 
        {//. 1, new new class () {} class inherits 
            public void run () 
             {// 2, override the run method 
                for (int I = 0; I <3000; I ++) 
                 {//. 3, the code to be executed, the write process in the run 
                     System.out.println ( "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); 
                    } 
             } 
        } .start (); 
        * implement Runnable 

new new the Thread (new new Runnable () 
        {//. 1, new new Interface () { } implement this interface 
            public void run () 
            {// 2, override the run method 
              for (int I = 0; I <3000; I ++)  
              {//. 3, the code to be executed, the write process in the run
              System.out.println ( "BB"); 
              }
            }
        }).start(); 

  

### 24.09_ multithreading (get names and settings name) (master)
* 1. Obtain name
* Get the name of the thread object by getName () method
* 2. Set name
* String type can be passed through the constructor's name
*
the Thread new new ( "XXX") {
public void RUN () {
for (int I = 0; I <1000; I ++) {
System.out.println (this.getName () + ".... aaaaaaaaaaaaaaaaaaaaaaa");
}
}
} .start ();

new new the Thread ( "yyy") {
public void RUN () {
for (int I = 0; I <1000; I ++) {
System.out.println (this.getName () + ".. ..bb ");
}
}
} .start ();
* thread object name may be provided by setName (String) method
*
the thread = T1 new new the thread () {
public void RUN () {
for (int I = 0; I <1000; i ++) {
System.out.println(this.getName() + "....aaaaaaaaaaaaaaaaaaaaaaa");
}
}
};

Thread t2 = new Thread() {
public void run() {
for(int i = 0; i < 1000; i++) {
System.out.println(this.getName() + "....bb");
}
}
};
t1.setName("芙蓉姐姐");
t2.setName("凤姐");

t1.start();
t2.start();

### 24.10_ multithreading (get an object the current thread) (control)
* Thread.currentThread (), the main thread may acquire
*
new new the Thread (new new the Runnable () {
public void RUN () {
for (int I = 0 ; I <1000; I ++) {
System.out.println (Thread.currentThread () getName () + "aaaaaaaaaaaaaaaaaaaaa ...");.
}
}
.}) Start ();

new new the Thread (new new the Runnable () {
public RUN void () {
for (int I = 0; I <1000; I ++) {
System.out.println (Thread.currentThread () getName () + "BB ....");
}
}
.}) Start ( );
Thread.currentThread (.) setName ( "I am the main thread"); // get a reference to the main function thread, and changed his name
System.out.println (Thread.currentThread () getName () );. // Gets the main function thread references, and get the name of
### 24.11_ multithreading (sleeping thread) (master)
* The Thread.sleep (ms, ns), the control current thread sleep several milliseconds 1 second 1 second = 1000 ms = 1000 * 1000 * 1000 nanoseconds 1000000000

the Thread new new () {
public void RUN () {
for (int I = 0; I <10; I ++) {
System.out.println (getName () + "aaaaaaaaaaaaaaaaaaaaaa ...");
the try {
the Thread.sleep (10 );
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}
}
} .start ();

new new the Thread () {
public void RUN () {
for (int I = 0; I <10; I ++) {
the System .out.println (getName () + "BB ...");
the try {
the Thread.sleep (10);
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}
}
} .start ();
## # 24.12_ multithreading (daemon threads) (master)
* setDaemon (), set a thread as a daemon thread, the thread does not perform alone, when other non-daemon threads are executed over, automatically exit
*
Thread t1 = new Thread() {
public void run() {
for(int i = 0; i < 50; i++) {
System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};

Thread t2 = new Thread() {
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(getName() + "...bb");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};

t1.setDaemon(true); //将t1设置为守护线程

t1.start();
t2.start();
### 24.13_ multi-threaded (thread join) (master)
* the Join (), the current thread is suspended until the end of the specified thread execution, the current thread to continue
after * join (int), you can continue to wait for the specified milliseconds
*
Final T1 = the Thread new new the Thread () {
public void RUN () {
for (int I = 0; I <50; I ++) {
System.out.println (getName () + "aaaaaaaaaaaaaaaaaaaaaa ...");
the try {
the Thread. SLEEP (10);
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}
}
};

the Thread T2 = new new the Thread () {
public void RUN () {
for (int I = 0; I <50; I ++) {
IF (I == 2) {
the try {
//t1.join (); // interruption added
t1.join (30); // added, there is a fixed time, and after a fixed time, continue to alternate execution
Thread. SLEEP (10);
} the catch (InterruptedException E) {

e.printStackTrace ();
}
}
System.out.println (getName () + "BB ...");

}
}
};

t1.start ();
t2.start ();
### 24.14_ multithreading ( comity thread) (understand)
* yield give up cpu

### 24.15_ multi-threaded (thread priority set) (understanding)
* setPriority () to set thread priority

### 24.16_ multithreading (synchronous code block) (master)
* 1. Under what circumstances need to be synchronized
* When multi-threaded, multiple sections of code executing at the same time, we want to process a piece of code executed in the CPU do not switch to another thread work. then you need to synchronize.
* If the two codes are synchronized, then the same period of time can only be performed in a piece of code is not executed before the end, will not execute another piece of code.
* 2. synchronized block
* use synchronized keyword plus a lock object to define a piece of code, which is called synchronous code block
* multiple synchronized block if the same lock object, then they are synchronized

{Printer class
Demo Demo new new D = ();
public static void PRINT1 () {
the synchronized (D) {// locked object can be any object, but locked code to ensure that the same lock can not be anonymous objects
System. out.print ( "black");
System.out.print ( "MA");
System.out.print ( "process");
System.out.print ( "order");
System.out.print ( "member ");
of System.out.print (" \ R & lt \ n-");
}
}

public static void print2 () {
the synchronized (D) {
of System.out.print (" pass ");
of System.out.print (" chi ");
of System.out.print (" broadcast ");
of System.out.print (" off ");
of System.out.print (" \ R & lt \ n-");
}
}
}
### 24.17_ multithreading (synchronous method) (master)
* Using a modification of the synchronized keyword method in all of the code are synchronized

{Printer class
public static void PRINT1 () {
the synchronized (Printer.class) {// locked object can be any object, but locked code to ensure that the same lock can not be anonymous objects
System.out.print ( "Black ");
System.out.print (" MA ");
System.out.print (" process ");
System.out.print (" order ");
System.out.print (" members ");
System.out .print ( "\ R & lt \ n-");
}
}
/ *
lock * non-static function is synchronous: the this
* static lock synchronization function is: bytecode object
* /
public static void the synchronized print2 () {
the System. out.print ( "pass");
System.out.print ( "wisdom");
System.out.print ( "broadcast");
System.out.print ( "off");
System.out.print ( "\ R & lt \ n-");
}
}

### 24.18_ multi-threaded (thread-safety issues) (master)
* When multiple threads concurrently work on the same data, it is possible to thread safety problems
* using synchronous technology can solve this problem, the source operating data synchronization, do not a plurality of threads operate together

public class Demo2_Synchronized {

/ **
* @param args
* Demand: railway ticket, a total of 100, sold by four windows.
* /
Public static void main (String [] args) {
TicketsSeller new new TicketsSeller T1 = ();
TicketsSeller T2 = new new TicketsSeller ();
TicketsSeller new new TicketsSeller T3 = ();
TicketsSeller new new TicketsSeller T4 = ();

t1.setName ( "window. 1");
t2.setName ( "window 2");
t3.setName ( "window. 3");
T4 .setName ( "window. 4");
t1.start ();
t2.start ();
t3.start ();
t4.start ();
}

}

class TicketsSeller the extends the Thread {
Private static int tickets = 100;
static Object obj Object new new = ();
public TicketsSeller () {
Super ();

}
TicketsSeller public (String name) {
Super (name);
}
public void RUN () {
the while (to true) {
the synchronized (obj) {
IF (tickets <= 0)
BREAK;
the try {
the Thread.sleep (10); // thread 1 sleep, sleep thread 2, the thread 3 sleep, sleep thread 4
} the catch (InterruptedException E) {

e.printStackTrace ();
}
System.out.println (getName () + "... this is the first" + tickets-- + "ticket number");
}
}
}
}

### 24.19_ multi-threaded (using the example of the train station ticket implement Runnable) (master)


### 24.20_ multithreading (deadlock) (understand)
* Multi-thread synchronization of the time, nested if synchronization code, using the same lock, it is possible deadlock
* Try not to nest

private static String s1 = "Chopsticks left ";
Private static String S2 =" chopstick Right ";
public static void main (String [] args) {
new new the Thread () {
public void RUN () {
the while (to true) {
the synchronized (S1) {
System.out.println (getName () + "... get" + s1 + "wait" + S2);
the synchronized (S2) {
System.out.println (getName () + "... get" + s2 + "open eat ");
}
}
}
}
} .start ();

new new the Thread () {
public void RUN () {
the while (to true) {
the synchronized (S2) {
System.out.println (getName () +" get ... "+ s2 +" wait "+ s1);
synchronized(s1) {
System.out.println (getName () + "... get" + s1 + "eat open");
}
}
}
}
} .start ();
}

### 24.21_ multi-threaded (thread-safe class the previous review) (master)
* A: Review said before thread-safety issues
* see the source code: the Vector, StringBuffer, Hashtable, Collections.synchroinzed (xxx)
* the Vector is thread safe, ArrayList is not thread-safe
* StringBuffer is thread-safe, StringBuilder is not thread-safe
* Hashtable is thread-safe, HashMap is thread safe
### 24.22_ multithreading (summary)

Guess you like

Origin www.cnblogs.com/sdrbg/p/11260447.html