Multi-thread safe handling

 Thread Safety

 

If there are multiple threads running at the same time, and these threads may run this code at the same time. Program each time you run the results and single-threaded operating results are the same, and also the values of other variables and expectations are the same, that is thread-safe .

 

Through a case study that demonstrates the thread safety problems:

 

Movie theater to sell tickets, we simulated a movie theater selling of votes . Suppose you want to play the movie is " Kung Fu Panda 3" , this movie's seat a total of 100 Ge ( this field a movie can only sell 100 tickets ) .

 

Let's simulate a movie theater ticket window, multiple windows at the same time to achieve sell " Kung Fu Panda 3" this movie tickets ( sold together multiple windows which 100 tickets )

 

Required window , threading simulated objects ; required votes , the Runnable Interface Subclass to simulate

 

Analog tickets :

 

 

test class

 

 

 

 

 

 

实,线程安全问题都是由全局变量及静态变量引起的。若每个线程中对全局变量、静态变量只有读操作,而无写操作,

一般来说,这个全局变量是线程安全的;若有多个线程同时执行写操作,一般都需要考虑线程同步,否则的话就可能影响线程安全。

 

线程为啥不安全展示图:

 

 

 

线程同步(线程安全处理Synchronized

 

java中提供了线程同步机制,它能够解决上述的线程安全问题。

 

线程同步的方式有两种:

 

方式1:同步代码块

 

方式2:同步方法

 

同步代码块

 

 

 同步方法

 

 

 

 

 

 Lock接口

 

线程状态:

 线程状态分为

新建状态:new

运行状态:Runnable

受阻状态:Blocked

等待状态:Waiting

休眠状态:Timed-Waiting

死亡状态:Terminated

 

Guess you like

Origin www.cnblogs.com/www1842564021/p/12312866.html