What is thread safety in Java? Synchronous, asynchronous

Source: Internet
Author: User
Tags thread class ticket

Threads are smaller units of execution than processes and are further divisions based on processes. Multithreading means that a process can produce multiple threads that are concurrently running at the same time during execution. The multi-process mechanism can utilize resources rationally and improve the running efficiency of the program. A process contains at least one thread (the JVM virtual machine start-up is multithreaded, with at least two threads: Main and garbage collection mechanism).

1. What is thread safety?

Process at run time in order to better utilize the resources to improve the efficiency of the operation, will produce multiple threads, but when the multiple threads run, the same resource will operate concurrently, also known as thread async, for example: Thread A, a, when the same linked list operation, if a to the linked list reads, Thread B writes the data to it at the same time. Obviously this is very bad. Then thread synchronization is required.

2, what is thread synchronization?

Thread synchronization: In layman's terms, when thread A is working on a resource, thread B and other threads must wait, and this resource cannot be manipulated at this time. That is, threads A and B do not concurrently access this resource according to the intended schedule.

3, Thread safety: for thread async, such a thread at run time is unsafe, so the introduction of synchronization.

There are two ways to implement multithreading in Java, which inherits from the thread class and implements the Runnable interface.
1 inherit from thread interface needs to implement the Run method,
public class Threaddemo extends thread{
private String name;
Public Threaddemo (String name) {
This.name=name;
}
Overriding the Run method in the thread class
public void Run () {
for (int i=0;i<=10;i++) {
System.out.println (name+ "Run i=" +i);
}
}
public static void Main (String [] name) {
New Threaddemo ("Thread A"). Start ();
New Threaddemo ("Thread B"). Start ();
}
}
It turns out that a thread, a, and a staggered run.

public class Runnabledemo implements runnable{
private String name;
Public Runnabledemo (String name) {
This.name=name;
}
@Override
public void Run () {
for (int i=1;i<=15;i++) {
System.out.println (name+ "Run i=" +i);
}

}
public static void Main (String [] args) {
Runnabledemo demo1=new Runnabledemo ("Thread A");
Runnabledemo demo2=new Runnabledemo ("thread B");
Thread thread1=new thread (DEMO1);//Instantiate thread class
Thread thread2=new thread (DEMO2);//Instantiate thread class
Thread1.start ();//Start thread
Thread2.start ();//Start thread
}
}
Note Starting multithreading must be implemented using the thread class

The difference between the thread class and the Runnable interface, if inherited from the thread class, is not suitable for multiple threads to share resources, and implements the Runnable interface can easily realize the resource sharing.

public class ThreadDemo2 extends thread{
private String name;
private int ticket=15;
public void Run () {
for (int i=0;i<=15;i++) {
if (ticket>0) {
SYSTEM.OUT.PRINTLN (name+ "Sell ticket: ticket=" +ticket--);
}
}
}
Public ThreadDemo2 (String name) {
This.name=name;
}
public static void Main (string[] args) {
ThreadDemo2 demo1=new ThreadDemo2 ("Thread A");
ThreadDemo2 demo2=new ThreadDemo2 ("thread B");
ThreadDemo2 demo3=new ThreadDemo2 ("Thread C");
New Thread (DEMO1). Start ();
New Thread (Demo2). Start ();
New Thread (DEMO3). Start ();
}
}
It turns out that thread A,b,c sold 15 tickets each.


public class RunnableDemo2 implements runnable{
private int ticket=10;

public void Run () {
for (int i=1;i<=5;i++) {
if (ticket>0) {
SYSTEM.OUT.PRINTLN ("Sell ticket: ticket=" +ticket--);
}
}
}
public static void Main (string[] args) {
RunnableDemo2 demo1=new RunnableDemo2 ();
New Thread (DEMO1). Start ();
New Thread (DEMO1). Start ();
New Thread (DEMO1). Start ();
}
}
The results are as follows: Sell ticket: ticket=10
Sell Tickets: ticket=9
Sell Tickets: ticket=8
Sell Tickets: ticket=7
Sell Tickets: ticket=6
Sell Tickets: ticket=5
Sell Tickets: ticket=4
Sell Tickets: ticket=3
Sell Tickets: ticket=2
Sell Tickets: ticket=1

Implementing the Runnable interface with inheriting from the thread class has the following advantages over implementing multi-threading

(1) Suitable for multiple threads with the same program code to handle the same resource

(2) Avoid the limitations of the Java single inheritance feature

(3) The code can be shared by multiple threads and the data exists independently, thus enhancing the robustness of the program.

4. Thread synchronization

Synchronization means that only one thread can run in the same time period, and other threads need to wait for the thread to finish before they can continue execution. Synchronization can solve the security problem of resource sharing in thread, which is done by synchronous code block and synchronous method.

1) synchronous code block format

Synchronized (synchronization object) {

Code blocks that need to be synchronized

}

public class Synchronizeddemo implements runnable{
private int ticket=5;
public void Run () {
for (int i=1;i<=5;i++) {
Synchronized (this) {
if (ticket>0) {
try{
Thread.Sleep (1000);
}catch (Exception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Sell ticket: ticket=" +ticket--);
}

}
}
}
public static void Main (string[] args) {
Synchronizeddemo demo1=new Synchronizeddemo ();
New Thread (DEMO1). Start ();
New Thread (DEMO1). Start ();
New Thread (DEMO1). Start ();
}
}

The results are as follows:

Sell Tickets: ticket=5
Sell Tickets: ticket=4
Sell Tickets: ticket=3
Sell Tickets: ticket=2
Sell Tickets: ticket=1

If you do not join the thread synchronization method, the ticket will appear negative

There is also a synchronization method

The format is as follows:

Synchronized method return type method name (parameter list) {

}

5, the life cycle of the thread/

1) Create status

2) Ready state

3) Operating Status

4) Blocking status

5) Termination Status

6, Add JS Understanding

Look at a piece of code first

var x = Document.getelementsbyname (data); var i;  for (i = 0; i < x.length; i++) {var value=x[i].id $.getjson (ctx +  '/sys/dict/description ', { Span class= "Hljs-keyword" >value: value}, function (data) {var str =  ' &nbsp;value+ "/>"; $ ( Tooltip-description [desc= ' +value+  

The intent of this code is to get all elements on the page based on the element name, then send the request to the background one after the other, will be displayed on the page according to the resulting data, in the code, the for loop should be an atomic operation, but $.getjson () is the asynchronous request data, the first request is not finished, The second one has started, causing data clutter, so you should modify the for loop to make it thread safe by adding a piece of code before the For loop:

var x = document.getelementsbyname (data); var i;$.ajaxsettings.   async = FALSE; for (i = 0; i < x.length; i++) {var value=x[i].id $.getjson (ctx +  '/sys/dict/description ', { Span class= "Hljs-keyword" >value: value}, function (data) {var str =  ' &nbsp;value+ "/>"; $ ( Tooltip-description [desc= ' +value+  

What is thread safety in Java? Synchronous, asynchronous

Related Article

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.