Basic concepts of threadingprocess and usage environment
A program is a collection of computer instructions that are stored on disk as files, and a process is an executing program, each of which has its own memory space and system resources.
The process is a running program, the Windows operating system is to support multi-process operating system, that is, the same time L can execute multiple programs, each program is in its own separate memory space, using its own assigned system resources. In fact, this statement is not accurate, a CPU at some point, the actual can only run a program, that is, a process. The so-called multi-process support, in fact, the CPU in a very fast alternating execution of multiple programs, for example, the use of Windows operating system can listen to songs, while surfing the internet and so on.
threading and usage environments
Threads are the basic unit of CPU scheduling and dispatch, and a process can consist of multiple threads that share the same storage space, making communication between threads easier. In a multi-process program, if you want to switch to another process, you need to change the location of the address space. However, in arrogance, this is not the case because they are in the same memory space. Just change the order of the runs.
Multithreading means that a single program can perform different tasks by running several different threads at the same time. The so-called at the same time, also depends on the CPU. If it is multiple CPUs, then run concurrently, and if it is a CPU, execute multiple threads depending on the system situation.
Thread Creation
There are generally two ways to create a thread:
1. Create a thread by implementing the Runnable interface.
2. Create a thread by inheriting the thread class.
creating threads through the Runnable interfacein Java, a thread is an object, but not all objects can be called threads. Only classes that implement the Runnable interface can be called threads. First look at the definition of the Runnable interface:
Public interface runnable{Public abstract void run ();
The runnable interface has only one abstract method run (). To implement this interface. As long as you implement this abstract method. As long as the class that implements this interface is qualified to be called a thread.
The structure for creating threads is as follows:
Thread T=new Thread (Runnable object);
An Runnable object is an object that implements the Runnable interface class. The "Run ()" method in the. Runnable object is called when the thread executes, and if you want to run the thread created above, you also need to invoke a method of the thread class.
T.start ();
Example:
public class threadtest{//Create test Two thread class, let it alternately transport a public static void main (String[]args) { Create objects C and C1 compute c=new compute (); Compute1 c1=new compute1 (); Create thread object T and T1 thread t=new thread (c); Thread T1=new thread (c1); T.start ();//Start Thread object T T1.start ();//Start thread object T1}}//create class with output number through LOOP statement classes Compute Implemeat s runnable{//create class to implement thread compute public void run () { Implementation method Run () for (int i=0; i<10;i++) {System.out. println (i); }}}//Create class Compute1 implements runnable{//Create a class that implements threads by looping through a loop statement compute1 public void Run () {//Implementation method run () for (int i=0;i<10;i++) {System.out.println ("This number is:" +i); } }}
Operation Result:
0
This number is: 0
1
This number is: 1
2
This number is: 2
3
This number is: 3
4
This number is: 4
5
This number is: 5
6
This number is: 6
7
This number is: 7
8
This number is: 8
9
This number is: 9
PS: In this program segment, two threads are created, but the results may be different after multiple runs. So why would you output a different result?
Because there are problems with the order of execution when the program is running. In Java technology, threads are typically executed through a scheduling pattern. The so-called preemptive scheduling mode refers to the fact that many threads are in a ready state, that is, waiting, but only one thread is actually running. The thread runs until it terminates, or the other has a higher priority to become operational. In the latter case, a low-priority thread is preempted by a high-priority thread and gets a run opportunity.
to create a thread by inheriting the thread class
In fact, the thread class itself implements the Runnable interface, so a thread is also created whenever a class can inherit the thread class and overwrite the "Run ()" method.
example:
public class threadtest{//Create test Two thread class, let it alternately transport a public static void main (String[]args) { Create objects C and C1 compute c=new compute (); Compute1 c1=new compute1 (); Create thread object T and T1 thread t=new thread (c); Thread T1=new thread (c1); T.start ();//Start Thread object T T1.start ();//Start thread object T1}}//create class with output number through LOOP statement classes COMPUTE extends thread{//Create class to implement thread compute public void run () { Implementation method Run () for (int i=0; i<10;i++) {System.out. println (i); }}}//Create class Compute1 extends thread{//Create a class that implements threads by looping through a loop statement compute1 public void Run () {//Implementation method run () for (int i=0;i<10;i++) {System.out.println ("This number is:" +i); } }}
The detailed use of these two methods:
Executorservice Implementing Java Multithreading
Use of Threads
priority of the threadthe order in which the threads are executed is a preemption, with a higher priority than the priority to get more execution time, and if you want a thread to run more time than other threads, you can resolve it by setting the priority of the thread.
Once a thread is created, it can be prioritized by invoking the set priority () method in the threads, as follows:
Public final void setpriority (int newpriority);
Newpriority is a positive integer between 1 and 10, the higher the value, the higher the priority, and the system defines some constant values as follows:
Public final static int Min_priority=1, which represents the lowest priority.
Public final static int Max_ priority=10, which represents the highest priority.
Public final static int norm_priority=5, which represents the default priority.
Example:
public class threadtest{//Create test Two thread class, let it alternately transport a public static void main (String[]args) { Create objects C and C1 compute c=new compute (); Compute1 c1=new compute1 (); Create thread object T and T1 thread t=new thread (c); Thread T1=new thread (c1); t. SETPRIORITP (n); T1.SETPRIORITP (1); T.start ();//Start Thread object T T1.start ();//Start thread object T1}}//create class with output number through LOOP statement classes COMPUTE extends thread{//Create class to implement thread compute public void run () { Implementation method Run () for (int i=0; i<10;i++) {System.out. println (i); }}}//Create class Compute1 extends thread{//Create a class that implements threads by looping through a loop statement compute1 public void Run () {//Implementation method run () for (int i=0;i<10;i++) {System.out.println ("This number is:" +i); } }}
Output Result:
0
1
2
3
4
5
6
7
8
9
This number is: 0
This number is: 1
This number is: 2
This number is: 3
This number is: 4
This number is: 5
This number is: 6
This number is: 7
This number is: 8
This number is: 9
At this point the output becomes very regular, because the program will output the number of threads to the highest priority, and the output of the Chinese character thread is the lowest priority of the system, so when the program executes, it will give the digital output thread more time to execute.
Hibernate and wake-up of Threads
The sleep of a threadA thread's hibernation is a state in which a thread is temporarily waiting, in layman's words, that the thread temporary I pays to stop running.
To achieve this functionality, you call the "sleep ()" Method of the Thread class. The sleep () method causes the thread to be in a state that is temporarily stopped at a specified time, until the specified time has ended, and the temporary stop state ends, and then continues to perform the task that is not completed. The method structure of the "Sleep ()" method is as follows
public static native void sleep (long Millis) throws Interruptedexcption
the "Millis" parameter refers to the number of milliseconds that the thread sleeps. The above code concerns the problem of throwing an exception, as there is no beginning to tell about throwing exceptions, so just know to throw an exception.
Wake on Threadthe wake of a thread means that the thread is allowed to enter the executable state from the Hibernate wait state, which can be implemented by invoking the method "interrupt ()".
Usage:
public class thread6{public static void Main (string[] args) { compute t=new compute (); T. Start () T. Interrupt (); }} Create a thread class in this class through hibernation to output different results class Compute extends thread{ int i = 0; public void Run () { //output corresponding information System.out.println ("Do Not Disturb at work"); try{ Sleep (1000000); } catch (Exception e) { System.out.priatla ("Oh, the phone is coming ');}}}
Threading Concessions
The so-called threading concession is to leave the currently running thread object out of the running state and let other threads run it by invoking the "yield ()" method. This method does not give the right to run to the specified thread, but allows the thread to let it run, and to whom it needs to see which thread is preempted.
Example:
Create a master Run class public class thread7{public static void Main (String[]args) { //Create two thread objects T and T1 compute t=new Compute (); Compute1 t1=new compute1 (); Start two threads T.start (); T1.start (); }} Create classes that output numbers by looping statements class Compute extends thread{ //Create an inherited thread class compute int i=0; Create member variable public void run () { //Implement Run () method for (int i=0;i<10;i++) { System.out.println (i); Yield (); Let thread pause } }}//Create class Compute1 extends thread{//create an inherited thread by looping statements output a number class compute1 public void Run () {//Implement run () method for (int i=0;i<10;i++) { System.out.println ("This number is:" +i); } }}
Results:
0
This number is: 0
This number is: 1
This number yu is: 2
This number is: 3
This number is: 4
This number is: 5
This number is: 6
This number is: 7
1
This number is: 8
This number is: 9
2
3
4
5
6
7
8
9
Judging from the running results. The 1th thread is less likely to run than the No. 0 thread because it always gives up the right to run
Thread Synchronization
As mentioned earlier, the running of a thread is obtained through a method called preemption. When one program runs halfway, it is suddenly preempted by another thread, where the thread is processing half of the data. And another thread is working on it, and then there's a duplication of data, and eventually the whole system gets messy.
Synchronization Block
A synchronization block is a method that enables a thread with an object's monitoring point to gain permission to run, and each object can only gain permission to run if it has this monitoring point. For example, a round table has 4 people to eat, but only one spoon, only one person in 4 can eat, and this person must be a person with a spoon, and this spoon is equivalent to the monitoring point in the synchronization block.
The structure of the synchronization block is as follows
Synchronized (someobject) {code Snippet}
"Someobject" is a monitoring point object that can be actually present, or it can be hypothetical. This monitoring point object is assumed in a number of program segments. In fact, this monitoring point, the equivalent of a lock, a thread on a lock, then the other threads will be shut out, will not be able to get this lock. This lock is not handed over to other threads until the thread has finished executing. After the other threads have been locked, lock their own programs and then shut out other threads.
Example:
Create a master Run class public class threadl0{public static void Main (string[] //Create two thread objects T, T1 and T2 COMPUTE t=new COMPUTE (' a '); Compute t1=new Computel (' B '); COMPUTE T2 "New compute (' C '); Start three threads T.start (); T1.start (); T2.start (); }} Create class Compute extends thread{char ch with output numbers through a loop statement ; Static Object Obj=new object (); Compute (char ch) { this.ch=ch; } public void print (CHAR-ch) {for (int i,0;i<10;i++) { System.out.print (ch);} } public void Run () { synchronized (obj) {for (int i=1;i<10;i++) { print (ch); System.out.println ();}}}
Results:
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
Aaaaaaaaa
BBBBBBBBB
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
BBBBBBBBB
CCCCCCCCC
Ccccccccc
Ccccccccc
Ccccccccc
Ccccccccc
Ccccccccc
Ccccccccc
Ccccccccc
CCCCCCCCC
When you add a watch point to the running program, the lock is automatically opened after the segment in the lock is executed, and the lock is preempted by another two threads. The program in this synchronization block is then executed repeatedly so that another thread executes after one thread finishes executing. The same data for multithreaded operations. There will be no chaotic phenomenon.
Synchronization Method
The method of synchronization is to synchronize the whole method. It is structured as follows:
synchronized void f () {code}
Example:
Create a master Run class public class threadl0{public static void Main (string[] //Create two thread objects T, T1 and T2 COMPUTE t=new COMPUTE (' a '); Compute t1=new Computel (' B '); COMPUTE T2 "New compute (' C '); Start three threads T.start (); T1.start (); T2.start (); }} Create class Compute extends thread{char ch with output numbers through a loop statement ; Static Object Obj=new object (); Compute (char ch) { this.ch=ch; } Synchronized void print (char ch) {for (int i,0;i<10;i++) { System.out.print (ch); } } public void Run () {for (int i=1;i<10;i++) { print (ch); System.out.println ();}}}
As you can see from the above results, the output of using synchronous blocks and synchronous methods is the same.
Example Analysisproducers and Consumers
1 Hamburger shops, with 1 cooks and a salesperson. The clerk is responsible for making hamburgers, the salesman is responsible for selling hamburgers, and of course there are 1 boxes for storing hamburgers. The chef kept making hamburgers and put them in the box, and when each guest came, the salesperson took out 1 hamburgers from the box and sold them. Suppose the premise is that guests every 1 seconds to 1, that is to say the salesperson 1 seconds to sell 1 hamburgers, and cook 3 seconds to do 1 hamburgers.
There are currently only 10 hamburgers (only 10 in the material) and 5 burgers in the box, please write a program code to show the relationship of the sale.
The code is as follows:
Design the Hamburger box class and use it as a monitoring point with the following code: Class Ham {//Create a box containing a hamburger as a Monitor class static object box = new Object (); Create object boxstatic int totalmaterial=10; About the material property of making hamburgers static int sales=0; About the sale of how many hamburgers attribute static int production=5; About the total number of hamburger properties} Design Chef class, the code is as follows: Class Hmaker extends thread//chef Thread class {//make method uses a synchronization block, in this function will continue to produce hamburger public void makes () {synchroaiaed (Ham.box) {//Create sync block (ham.production) + +; try{ham.box.notify (); }catch (Exception e) {}}}public void Run () {//rewrite the Run () method//Use a circular statement to ensure that the hamburger material is continuously Hamburger while (ham.production
The number of products that cooks can make hamburgers should be less than the total amount of material. Under this precondition, if the product is not equal to zero, let the chef tell a voice: the hamburger came up, once, total how many. Next start 3 seconds to do 1 hamburgers, done, and then notify a voice: The hamburger came up, a total of a few. In addition, as long as the hamburger in the box is not equal to zero, inform the salesperson can sell. And the salesperson class, mainly sells hamburgers, sells 1 every 1 seconds, if the hamburger inside the box equals zero, informs the customer: the hamburger has not, needs to wait.
Results:
Chef A: Hamburgers Come (total 5)
Salesperson: Good customer, hamburger up (total 1 sold)
Salesperson: Good customer, hamburger up (total 2 sold)
Chef A: Hamburgers Come (total 4)
Salesperson: Good customer, hamburger up (total 3 sold)
Salesperson: Good customer, hamburger up (total 4 sold)
Salesperson: Good customer, hamburger up (total 5 sold)
Chef A: Hamburgers Come (total 2)
Salesperson: Good customer, hamburger up (total 6 sold)
Salesperson: Customer Good hamburger Up (sold 7 total)
Chef A: Hamburgers Come (total 1)
Chef A: Hamburgers Come (total 2)
Java System Learning (10)--------Thread