Java multi-thread learning notes-thread security

Source: Internet
Author: User

What is thread security first? Java Memory Model: A simple understanding is to copy data from the system memory to the jvm's working memory-> process variables in the jvm memory-> write data back to the system memory after jvm processing is complete. For example, the following operation is: copy I from the system memory to the working memory> Add I in the working memory to 10> write the value of 10 in the working memory back to the system memory.

Assume that I is the deposit data of the bank, I = 100. Now I use a B to execute the I = I + 10; (save 10 RMB) operation at the same time, the process may be like this due to asynchronous execution by default:

1. Thread A reads I from the system memory.
2. The B thread reads I from the system memory.
3. Thread A executes I + 10.
4. Line B executes I + 10.
5. Thread A writes 110 back to the system memory. The I value in the memory is 110.
6. The B thread writes 110 back to the system memory. The I value in the memory is 110 ,.

Obviously, the result of this process is incorrect, with less money saved by one person.

Synchronized keyword

I understand that this keyword is used to control objects that have only one reference in the working memory in the case of multithreading.

Multi-thread security instance:

The Code is as follows: Copy code

Package threads;

Public class TestIPP
{

Public static void main (String [] args) throws InterruptedException
{
Num num = new Num (100000 );

Thread plus = new Plus (num );
Thread cut = new Cut (num );

Plus. start ();
Cut. start ();
Plus. join ();
Cut. join ();

System. out. print (num. getNum ());
}

Public static class Num
{
Int num;

Public void plus ()
{
Num ++;
}

Public void cut ()
{
Num --;
}

Public Num (int num)
{
This. num = num;
}

Public int getNum ()
{
Return this. num;
}
}

Static public class Plus extends Thread
{
Num num;

Public Plus (Num num)
{
This. num = num;
}

Public void run ()
{
Synchronized (num ){
For (int I = 0; I <5; I ++ ){
Num. plus ();
System. out. println ("+ 1 ");
}
}
}
}

Static public class Cut extends Thread
{
Private Num num;

Public Cut (Num num)
{
This. num = num;
}

Public void run ()
{
Synchronized (num ){
For (int I = 0; I <5; I ++ ){
Num. cut ();
System. out. println ("-1 ");
}
}
}
}
}

Example

The Code is as follows: Copy code

Import java. io .*;
// Multi-thread programming
Public class MultiThread
{
Public static void main (String args [])
{
System. out. println ("I am the main thread! ");
// Create thread instance thread1 below
ThreadUseExtends thread1 = new ThreadUseExtends ();
// When thread2 is created, the THhreadUseRunnable class instance that implements the Runnable interface is used as the parameter.
Thread thread2 = new Thread (new ThreadUseRunnable (), "SecondThread ");
Thread1.start (); // start thread thread1 to make it ready
// Thread1.setPriority (6); // set the priority of thread1 to 6.
// The priority determines who occupies the cpu and starts running the ready thread when the cpu is empty.
// Priority ranges from 1 to 10, MIN_PRIORITY, MAX_PRIORITY, norm_priority ority
// The New thread inherits the parent thread priority created by her. The parent thread usually has the normal priority 5NORM_PRIORITY.
System. out. println ("the main thread will be suspended for 7 seconds! ");
Try
{
Thread. sleep (7000); // The main Thread is suspended for 7 seconds.
}
Catch (InterruptedException e)
{
Return;
}
System. out. println ("back to the main thread! ");
If (thread1.isAlive ())
{
Thread1.stop (); // If thread1 still exists, kill it
System. out. println ("thread1 sleep too long, the main thread killed thread1! ");
}
Else
System. out. println ("thread1 was not found in the main thread, and thread1 woke up and the execution ended! ");
Thread2.start (); // start thread2
System. out. println ("the main thread will be suspended for another 7 seconds! ");
Try
{
Thread. sleep (7000); // The main Thread is suspended for 7 seconds.
}
Catch (InterruptedException e)
{
Return;
}
System. out. println ("back to the main thread! ");
If (thread2.isAlive ())
{
Thread2.stop (); // If thread2 still exists, kill it
System. out. println ("thread2 sleep too long, the main thread killed thread2! ");
}
Else
System. out. println ("thread2 is not found in the main thread. thread2 is awake and the execution is finished! ");
System. out. println ("program end press any key to continue! ");
Try
{
System. in. read ();
}
Catch (IOException e)
{
System. out. println (e. toString ());
}
} // Main
} // MultiThread
Class ThreadUseExtends extends Thread
// Inherit the Thread class and implement its abstract method run ()
// Create an instance of this Thread subclass as appropriate to implement the multithreading mechanism
// After a thread is started (that is, it enters the ready state), once the CPU is obtained, its run () method is automatically called.
{
ThreadUseExtends () {}// Constructor
Public void run ()
{
System. out. println ("I Am a Thread sub-class Thread instance! ");
System. out. println ("I will suspend for 10 seconds! ");
System. out. println ("back to the main thread. Please wait. The main thread has not woken up just now! ");
Try
{
Sleep (10000); // hangs for 5 seconds
}
Catch (InterruptedException e)
{
Return;
}
// If the run () method is executed in sequence, the thread ends automatically without being killed by the main thread.
// However, if the sleep time is too long, the thread remains alive and may be killed by stop ().
}
}
Class ThreadUseRunnable implements Runnable
// Implement the run () method in the Runnable interface, and then implement the class of the run () method.
// Create a Thread instance for the parameter
{
// Thread thread2 = new Thread (this );
// Use this class that implements the run () method in the Runnable interface as the parameter to create a Thread instance of the Thread class
ThreadUseRunnable () {}// Constructor
Public void run ()
{
System. out. println ("I Am a Thread class Thread instance and take the class that implements the Runnable interface as the parameter! ");
System. out. println ("I will suspend for 1 second! ");
System. out. println ("back to the main thread. Please wait. The main thread has not woken up just now! ");
Try
{
Thread. sleep (1000); // suspended for 5 seconds
}
Catch (InterruptedException e)
{
Return;
}
// If the run () method is executed in sequence, the thread ends automatically without being killed by the main thread.
// However, if the sleep time is too long, the thread remains alive and may be killed by stop ().
}
}
// Modify the sleep time or priority of the program, for example, setPriority ()

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.