Some understanding of Threading Basics (ii)

Source: Internet
Author: User

One, the thread scheduling and control

Usually the computer only has one cpu,cpu at a time only executes one command, the thread only then obtains the CPU time slice, namely the use right, can execute the command. On a single-core CPU machine, threads do not run in parallel. Java Virtual machine is mainly responsible for thread scheduling, access to the use of the CPU, there are two scheduling models: time-sharing scheduling model and preemptive scheduling model, Java use preemptive scheduling model.

Time-sharing scheduling model: All threads take turns using the CPU's right of use, evenly allocating each thread to occupy the CPU of the chip

Preemptive scheduling model: high-priority threads get more CPU time slices, and if the threads have the same priority, they are randomly selected.

Below we will learn how to use the thread in Java code, generally we do not write multi-threaded code in the work, but if you are writing server-side code, such as in IBM or the communication between the machine, write a server-side code, then we must consider multithreading, Normal we use the server like Tomcat has been the bottom-level implementation of multithreading.

1. Some basic methods of threading

(1) Gets the current thread object Thread.CurrentThread ();

(2) naming the thread t.setname ("T1");

(3) Gets the name of the thread T.getname ();

 Public class_04 thread Scheduling { Public Static voidMain (string[] args) {//How do I get the current thread object? //The thread that the saved memory address points to is the "main threaded object"Thread t=Thread.CurrentThread (); //gets the name of the threadSystem.out.println (T.getname ()); Thread T1=NewThread (NewProcessor03 ()); //Naming ThreadsT1.setname ("T1");                T1.start (); Thread T2=NewThread (NewProcessor03 ()); //Naming ThreadsT2.setname ("T2");    T2.start (); }}classProcessor03Implementsrunnable{ Public voidrun () {//The thread to which the memory address is saved points to is "T1 thread object"Thread t=Thread.CurrentThread ();    System.out.println (T.getname ()); }}

2. Priority of Threads

Threads with high thread priority get more CPU time slices, that is, the chances of getting executed are greater, priority 1-10

The priority of the thread is divided into three kinds: max_priority (highest level) (10); Min_priority (Minimum level) (1); Nom_priority (Standard) default (5)

Gets and sets the priority method for the thread to Thread.getpriority () and thread.setpriority (),

From the running results can be seen T1 thread and T2 thread snatch CPU time slice, because set up the priority of T1 higher, so T1 Rob time slice will be relatively more, so execute more

  

3, Thrad.sleep (ms), thread sleep method, about thread hibernation there are a few points to note:

1.thread.sleep;

The 2.sleep method is a static method

3. The function of this method, blocking the current thread (review the execution flow of a thread), freeing up the CPU for other threads

    

4. This method is a static method, so "reference." and "Class name." is the same.

In the following code, T.sleep is equivalent to Thread.Sleep, so blocking is not the T thread, but the main thread of the block.

 Public class_07 face Question { Public Static voidMain (string[] args)throwsexception{Thread T=NewProcessor07 (); T.setname ("T");        T.start (); //equivalent to Threadsleep//Thread.Sleep () is a static method, so T.sleep () is equivalent to Thread.Sleep ()//so the T-thread is not blocked, and blocking is the main pathT.sleep (5000); }}classProcessor07extendsthread{ Public voidrun () { for(inti=0;i<3000;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "---->" +i); }    }}

5. How to interrupt hibernation

(1) Using the exception mechanism T.interrupt (), this interrupt triggers a interrupted exception that can be exited from hibernation.

    

(2) Normal termination, correct stop a thread, add an expression bit outside

    

Second, thread synchronization (locking)   

1. Asynchronous programming model and synchronous programming model.
Asynchronous programming Model: T1 thread executes T1, T2 thread executes T2. Two threads who don't wait for WHO
Synchronous programming Model: The T1 thread and the T2 thread execute when the T1 thread must wait for the T2 thread to execute after the T1 thread executes, which is the synchronous programming model
2. When do you synchronize? Why do we introduce thread synchronization?
1. For data security. The efficiency is not considered for the time being, although the application usage is reduced, but in order to ensure that the data is secure, the synchronization mechanism must be added, the thread is synchronous, so the program becomes single-threaded, like two straight lines

It turns out to be parallel, and now it's going to be joined together into a line.
For example, in real life, I share a bank account with you, at this time there are 50,000 dollars in this account, today I took 20,000 yuan from this account, just out, in the account has not lost 20,000 dollars when (at this time the account is 50,000, but I have taken 20,000),
You also visit this account to take 30,000 dollars, when you return to the account is 50,000 minus 30,000, the account also has 20,000, this is the feedback information to withdraw money also returned, the account left 30,000. The end result is, the account originally has 50,000, I take 20,000, you take 30,000, the account also has 30,000, this

We will use this example to illustrate the account security issues that arise.

2. What are the conditions to use thread synchronization?
(1): Must be a multithreaded environment
(2): Multi-threaded environment sharing the same data
(3): Shared data involves modification operations

The following program shows the withdrawal example, first of all we look at not using the thread synchronization mechanism, multi-threaded simultaneous withdrawal of the same account, what will happen?

First we create an account type Demo account with the name and account amount, which provides a withdraw () withdrawal method followed by the creation of the Processer () class to implement the Runnable interface for multithreading

Adding an account class to the constructor, using the withdrawal method in the run () method, creating a new account in the main method, creating a multi-threading, we added a 1s sleep delay to the withdraw () method in order to be able to implement security issues.

So when the T1 thread, or the T2 thread executes, after one thread executes, the other thread runs the method within 1s, and the other thread takes the account balance that is not the remaining balance of the first thread. But the beginning of the balance, I

We saw that the final result was that T1 went to T2 and took 1000, but there were 4000 dollars left.

 Public class_00 thread synchronization plus lock { Public Static voidMain (string[] args)throwsexception{//Create a public accountAccount act=NewAccount ("actno--01", 5000.0); //create a thread to withdraw money from the same accountPorcessor p=Newporcessor (ACT); Thread T1=NewThread (P); Thread T2=NewThread (P);        T1.start (); //T1.sleep (+);T2.start (); }}//Withdrawal ThreadclassPorcessorImplementsrunnable{//AccountAccount Act; //Constructorporcessor (Account Act) { This. act=Act; }     Public voidrun () {Act.withdraw (1000.0); System.out.println ("Withdrawal 1000 successful, balance:" +act.getbalance ()); }}//Accountclassaccount{PrivateString Actno; Private Doublebalance;  PublicAccount () {};  PublicAccount (String Actno,Doublebalance) {         This. actno=Actno;  This. balance=balance; }    //Setter and Getter methods     PublicString Getactno () {return  This. Actno;}  Public voidSetactno (String actno) { This. actno=Actno;}  Public DoubleGetBalance () {return  This. Balance;}  Public voidSetbalance (DoubleBalance) { This. balance=balance;} //provide a way to withdraw money from outside     Public voidWithdraw (DoubleMoney) {//make a withdrawal of your current account        DoubleBefore= This. Balance; Doubleafter=before-Money ; //Delay        Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        //Update         This. Setbalance (after); }}

Operation Result:

Withdrawal 1000 successful, balance: 4000.0 withdrawal 1000 successful, balance:4000.0

3. Using Thread synchronization synchronized keywords

Synchronization principle:

Principle: T1 thread and t2 thread, T1 thread execution into the withdraw () method, encountered the Synchronized keyword, will go to find this object lock (essentially, each object has a 0 and 1 of the logo, we image called it as a lock), If the This object lock is found to execute the program in a synchronous statement block, the T1 thread returns the object lock of this when the code in the synchronization statement block ends.
In this program, the T1 thread executes the synchronous statement block process, if T2 also come over to execute the following code, also encountered the Synchronized keyword, will also go to the object lock of this, but the object lock is held by the T1, can only wait for this object lock return to execute T2 thread,

That is to say, when the T1 thread is in sleep () 1s, the t2 thread also executes here, discovering that T1 still holds the lock and can only wait for the T1 thread to lose all the money in the account to execute the T2 thread's code. We found that the result of the operation was correct.

But as we run, we find that the running time is getting longer. Because T2 threads will wait.

classaccount01{PrivateString Actno; Private Doublebalance;  PublicAccount01 () {};  PublicACCOUNT01 (String Actno,Doublebalance) {         This. actno=Actno;  This. balance=balance; }    //Setter and Getter methods     PublicString Getactno () {return  This. Actno; }     Public voidSetactno (String actno) { This. actno=Actno; }     Public DoubleGetBalance () {return  This. Balance; }     Public voidSetbalance (Doublebalance) {         This. balance=balance; }    //provide a way to withdraw money from outside//Public void synchronized withdraw (double money) {//} synchronized is added to the member method, and the thread takes away the This object lock     Public voidWithdraw (DoubleMoney) {//make a withdrawal of your current account//Put the code that needs to be synchronized in the synchronization statement block        synchronized( This){            DoubleBefore= This. Balance; Doubleafter=before-Money ; //Delay            Try{thread.sleep (1000);}Catch(Exception e) {}//Update             This. Setbalance (after); }    }}

Operation Result:

Withdrawal 1000 successful, balance: 4000.0 withdrawal 1000 successful, balance:3000.0

4. Use the Setdaemon () method to add a daemon thread.

From the thread type can be divided into, the user thread (all the above is the user thread), and the other is the daemon thread. The daemon thread is like this, all the user threads end the life cycle and the daemon thread ends the life cycle
As long as there is a user thread present, the daemon thread will not end, for example, the famous garbage collector in Java is a daemon thread, and it will only end if all the threads in the application end.

The daemon threads are generally executed indefinitely. We can use the Setdaemon () method to turn a thread into a daemon thread

If the following program does not have the Setdaemon () method, then the T1 thread will run, but with the Setdaemon () method, T1 becomes the daemon thread, and when the main thread finishes running, the T1 thread ends.

 Public class_00 Daemon Thread { Public Static voidMain (string[] args)throwsexception{Thread T1=NewProcessor (); T1.setname ("Daemon Thread"); //Modify the T1 user thread to a daemon threadT1.setdaemon (true);        T1.start ();  for(inti=0;i<10;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "-+" +i); Thread.Sleep (1000); }    }}classProcessorextendsthread{ Public voidrun () {intI=0;  while(true) {i++; System.out.println (Thread.CurrentThread (). GetName ()+ "-+" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}

Some understanding of Threading Basics (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.