Java learning diary (thread)

xiaoxiao2021-03-06  73

First, the concept of thread: The thread is similar to the process, which is a code that completes a particular function. It is a single order stream control in the program; but the process is different, the same type of thread is shared with a memory space and a set of groups. System resources, and thread itself data typically only only the microprocessor register data, and a stack used in the execution of the program. Therefore, the system is generating a thread or when switching between each thread, the burden is much smaller than the process. For this reason, the thread is called light-weight process. A plurality of threads can be included in a process.

A thread is a sequential control flow within a program. 1. Process: Each process has independent code and data space (process context), and the overhead of the process switching. 2. Thread: Lightweight Process, the same type thread sharing code and data space, each thread has a separate runtime stack and program counter (PC), and the overhead of thread switches. 3. Multi-process: In the operating system, you can run multiple task programs at the same time. 4. Multithread: In the same application, there are multiple sequential flows simultaneously.

Java is inherently supporting multi-threaded, all classes are defined under multithreading, and Java uses multithreading to make the entire system as an asynchronous system. 1. Virtual CPU, package in the java.lang.Thread class. 2. The code executed by the CPU is passed to the THREAD class. 3. The data processed by the CPU is passed to the THREAD class.

Second, the thread constructive thread example represents the real thread in the Java interpreter, which can start thread, termination thread, thread hang, etc., each thread is defined in Java's software package java.lang through class Thread, Its constructor is:

Public Thread (ThreadGroup Group, Runnable Target, String Name);

Among them, group indicates the thread group to which the thread belongs; Target actually performs the target object of the line, it must implement the interface runnable; Name is the thread name. Each thread in Java has its own name, Java provides a different Thread class constructor, allowing the thread to specify the name. If Name is NULL, Java automatically provides a unique name. When a parameter of the above-described configuration method is NULL, we can get the following construct:

public Thread (); public Thread (Runnable target); public Thread (Runnable target, String name); public Thread (String name); public Thread (ThreadGroup group, Runnable target); public Thread (ThreadGroup group, String name);

A class declaration can act as a thread body in the interface runnable in the interface runnable (): public void run ();

Any object that implements interface runnable can be used as a thread target object, and the THREAD itself also implements the interface runnable, so we can implement line-enforcement through two ways. (1) Define a thread class, which inherits the threaded Thread and rewritten the method Run (), at which time the target target can be null when initializing the instance of this class, indicating that the thread body is executed by this instance. Since Java only supports single inheritance, the classes defined by this method cannot inherit other parent classes.

(2) Provide a class of interface runnable as a thread target object. When initializing a thread class or thread subclass, pass the target object to this thread instance, the thread body Run () is supplied by the target object. . At this time, the class that implements the interface runnable can still inherit other parent classes.

Third, the state of the thread is all threads to complete its operation through a method Run () of a particular THRead object, and the method Run () is called a thread body. The figure below shows the different status of the Java thread and the method of converting the call between the status. 1. Creating a state (New Thread) When performing the following statements, thread is in place: thread mythread = new thread (); When a thread is created, it is just an empty thread object, the system does not assign resources for it. .

2. Runnable "thread mythread = new thread (); mythread.start (); When a thread is running, the system assigns the system resources it needs to run and call thread operations. Method, this is such that the thread is in a runnable state. It is important to note that this state is not running in the run, because the thread may actually run it actually. Since many computers are single-parallel, it is impossible to run all running threads at the same time, and Java's running system must be scheduled to ensure that these threads share the processor. 3. NOT RUNNABLE) There are several reasons for entering the uncomfortable state: 1) Call the SLEEP () method; 2) Call the SUSPEND () method; 3) is waiting for a conditional variable, thread calling Wait ) Method; 4) The input and output streams occur in the output stream; the uncomfortable state is also referred to as blocking state (Blocked). For some reason (input / output, waiting message, or other blocking case), the system cannot perform a state of threads. At this time, even if the processor is idle, the thread cannot be performed.

4. The termination of the Dead State (DEAD) thread can generally be implemented in two ways: natural undo (thread execution) or stopped (call the stop () method). It is not recommended to terminate the thread by calling STOP (), but let the thread are executed.

Fourth, some long use of thread 1. Sleep (long Millis) method is a static method, that is, we can call it directly, such as thread.sleep (5000) means that the thread that is currently running Stop work Wait 5000 milliseconds. One thing to note is that it cannot be sure that this thread will be executed immediately after 5,000 milliseconds.

2. Interrupt () This method is used to interrupt a thread (it feels more appropriate to say that in sleep is more appropriate). The role of this method can take an example: public class testinterrupt extends thread {/ ** Creates a new instance of testinterrupt * / public testinterrupt () {}

Public void run () {TRY {

For (int i = 0; i <5; i ) {system.out.println ("Running the first loop" i);} thread.sleep (10000);

For (int i = 6; i <10; i ) {system.out.println ("Running the second loop";}

} catch (interruptedException IE {system.out.println ("Sleep Interrupted In Run ()"); for (int i = 11; i <15; i ) {system.out.println ("Running The Third Loop" i);

}

}

Public static void main (string [] args) {testinterrupt ti = new testinterrupt (); thread t = new thread (ti); t.start ();

// delay for a few seconds to let the Other thread get going try {thread.sleep (2500);} catch (interruptedException IE) {system.out.println ("Sleep Interrupted In Main ()");}

System.out.Println ("About to Wake Up The Other Thread"); T.Interrupt (); System.out.Println ("EXITING");

}

In the above example, if there is no T.interropt (), the program is running is for (int i = 6; i <10; i ) {system.out.println ("Running the second loop i);} It is the content in catch in Catch.

3. Join () and Join (long Millis) Join () This function is to make the thread currently running, such as stopped, until this thread b call Join () method is executed, then continue Thread a; see a good example: public class testjoin1 Extends thread {/ ** creates a new instance of testjoin1 * / public testjoin1 () {}

Public void run () {TRY {

For (int i = 0; i <5; i ) {system.out.println ("Running the first loop";} thread.sleep (1000);

For (int i = 6; i <10; i ) {system.out.println ("Running the second loop";}

} Catch (InterruptedException IE {system.out.println ("Sleep Interrupted In Run ()");

}

Public static void main (string [] args) {try {testjoin1 ti = new testjoin1 (); thread t = new thread (ti); t.start (); t.join ();

For (int I = 11; i <15; i ) {system.out.println ("Running the third loop i);}} catch (interruptedException IE {system.out.println (" Join Interrupted In Run) ) ")

System.out.println ("EXITING");

}} The result of this program is to let T. Join () time running the thread (actually MAIN) is put on hold, finish all the contents of this thread, and then return to the main thread to continue doing T.JOIN (); The remaining content after the statement. If the t.join () is removed, the result of running on the general computer should be the content of the main content to make the contents of the T-thread.

Join (long Millis) This method and Join () method are similar, all of which are being executed, and the contents of the thread B of the method B. of the method of calling Join (long Millis). But behind the Millis parameters determine whether the thread can be prioritized (how many milliseconds representing the Millis representative), Millis Hazith after B thread, even if it is not running, it will return to thread a. A program underneath can be very good. Description This question: Public class testjoin2 extends thread {

/ ** CREATES A new instance of testjoin2 * / public testjoin2 () {} public void run () {TRY {

For (int i = 0; i <5; i ) {system.out.println ("Running the first loop" i);} thread.sleep (3500);

For (int i = 6; i <10; i ) {system.out.println ("Running the second loop";}

} Catch (InterruptedException IE {system.out.println ("Sleep Interrupted In Run ()");

}

Public static void main (string [] args) {TRY {TestJoin2 T2 = new testjoin2 (); thread t = new thread (t2); t.start (); t.join (3000);

For (int I = 11; i <15; i ) {system.out.println ("Running the third loop i);}} catch (interruptedException IE {system.out.println (" Join Interrupted In Run) ) ")");} System.out.println ("exiting from main");

}

After reading so much, it seems that it is easy to generate a misunderstanding Join () This function is to let the thread B-priority (first) of this method. In fact, the fact is not like this, Join () role as above Say, it can only let the current running thread a shelves, etc., etc., the B executes will start executing a. The program under the bottom can make this misunderstandings: public class test extends thread {public test (string a) {super (a);} public void run () {system.out.println (this.getname ());} public static void main (string [] args) {test a = new test ("a"); test b = New test ("b"); test c = new test ("c"); a.Start (); b.Start (); c.Start (); try {c.join ();} catch (Exception E ) {} System.out.println ("this is main!");}}

Looking at the result is A, B is first executed first, then C, finally main ^^;

4. About Synchronized The purpose of this keyword is to let several threads can synchronize and give a simplest example. There are 20 tickets for a cinema to sell, it has three taxpants. Write a program to confirm that the result of SYNCHRONIZED is good, you need to use the SLEEP () function to create this possible (thread execution timing noble, no need to expect): public class sell {public static void main (String " ] args) {SellThread Sell = New Sellthread (); thread sell1 = new thread (Sell, "Sellman1"); thread sell2 = new thread (Sell, "Sellman2"); thread sell3 = new thread (Sell, "Sellman3") Sell1.Start (); Sell2.Start (); Sell3.Start ();}}

Class Sellthread Implements Runnable {Private Int i = 20; Public Void Run () {While (TRUE) {IF (i> 0) {Try {thread.sleep (100);} Catch (Exception E) {} system.out. PRINTLN (Thread.currentThread (). getname () "Sell" i -);}}}}

The result is a total of 22 tickets (it is estimated that the cinema is nothing more than the ticket. It will be very happy, but it will face an angry customers ....) This time our synchronized should play a role ^ ^ The modification is as follows: public class sell2 {public static void main (string [] args) {Sellthread sell = new sellt (); thread sell1 = new thread (Sell, "Sellman1"); thread sell2 = new thread (Sell, " Sellman2 "); Thread Sell3 = New Thread (Sell," Sellman3 "); Sell1.Start (); Sell2.Start (); Sell3.Start ();}}

Class Sellthread Implements Runnable {Private Int i = 20; String a = "Now OK!"; Public Void Run () {While (True) {synchronized (a) {if (i> 0) {Try {thread.sleep (100 );} Catch (exception e) {} system.out.println (thread.currentthread (). Getname () "Sell" i -);}}}}}

This will only sell 20 tickets. In the parentheses in synchronized (), it is required to be a class object, so we can't write i directly in parentheses, just define a string object A, a sign flag (I don't know what to say, I can use it for 1 means, such a ticket seller Selln's ticket line will get A after he can start selling tickets, and he puts A this object sign flag is 0, then other The thread of the ticket seller sells tickets found that they couldn't take A. They only put them on hold. Also until the SellN's ticket thread released A, A flag flag became 1, this time the other ticket seller's ticket sales Threads can compete, see who first gets A. However, String A and the ticket have nothing to do, so we can use this to replace the synchronized () A, it does not say the THIS object is the same as the effect. It can be executed. There are two easy misunderstandings: (1). After a thread gets the object in synchronized parentheses, the thread that is not required to get this object can not be executed. Actually, other threads are also Can be executed, but when they execute the objects in synchronized, they found that the target's flag flag is 0, so it can only be put on hold. (It seems that lucky goddess can only take care of a person at the same time, so we use synchronized to make threads at the time of sacrificing efficiency, so don't need to use it.

(2) After a thread gets the object in the synchronized parentheses, any other thread cannot be executed, in fact, if other other objects that do not need synchronized can continue to execute threads or threads in the brackets of Synchronized Run together.

Some methods have been added to synchronized. In fact, this time is the caller of this method, that is, the sign flag of this method is 0. He can't do it with other thieves that need to be run, but you can do not need. This THIS object is running together.

5. Wait () and Notify () or NOTIFYAll () This several functions are to make several synchronous threads execute in a certain order. It is used with synchronized (), set () in Obj. One thing to note is that we should let the thread that need Obj.wait first start. Because the execution order is the thread A of Obj.wait () first start, then it runs to Obj.wait (), enters the shelving status, let other threads first execute. So the thread b with obj.notify () started, until B is executed to obj.notify () (Obj.Notify () is actually notified because of the thread of obj.wait () is put on hold: " You "), B is put on hold, then continue to make a content after the Obj.wait (). So if we let the thread B with obj.notify () first run, then B is executed, B is executed Obj.notify () did not find threads that entered the shelving status due to obj.wait (). Then start doing thread a with obj.wait (). A runs to obj.wait () to enter the shelving state, Waiting for Obj.Notify () in another thread to wake it, but unfortunately it will never wait, because the thread with obj.notify () has been found in the thread of the shelves, it is unfortunately Didn't find it. So thread A has been put on hold ... (I feel a bit like a love drama ...); give an example well: public class threadtest {public static void main (String [] args) {Storage Stor = New Storage (); Counter a = new counter (stor); printer b = new printer (stor); a.Start (); b.start ();}}

Class Storage {public INT i = 0;} Class Counter Extends Thread {Private Storage A; Public Counter (Storage Stor) {A = Stor;} PUBLIC VOID RUN () {System.out.Println ("hi"); try { Sleep (100);} catch (exception e) {} int i = 0; While (i <5) {synchronized (a) {system.out.println ("counter"); AI = (int) (Math.random () * 50); System.out.Println (AI); a.notify ();} system.out.println ("counter2"); i;}}}

Class Printer Extends Thread {Private Storage A; Public Printer (Storage Stor) {A = Stor;} Public Void Run () {INT I = 0; While (I <5) {Synchronized (a) {System.out.Println "Printer"); try {a.wait ();} catch (interruptedexception e) {} system.out.println (ai);} system.out.println ("printer2"); i;}}}

After running, Try {Sleep (100);} catch (exception e) {} comes out and then look at the run results.

There are still two points: (1). If several threads enter the shelving, then as long as an obj.notifyAll () is executed, they can run the state, but who is running first. I know.

(2) .Sleep () and WAIT () Sometimes, the same function can be noted, but the thread.sleep (long A) is over A milliseconds, indicating that the thread is not executed immediately. Thread.wait () one but accepting thread.notify () is immediately performed immediately.

6 ......... ^^

转载请注明原文地址:https://www.9cbs.com/read-91762.html

New Post(0)