How Java solves thread-safety issues in a total of two ways
1. Synchronizing code blocks
Synchronized (Sync monitor) {
Code that needs to be synchronized (the code that operates the shared data)
}
Synchronization Monitor: An object to act as a thread that gets the monitor and executes the code in parentheses. Generally called locking
The role of a synchronous lock ensures that, at any time, a thread can execute code in the synchronization lock,
Note:the implement Runnable interface and the extends thread class are a bit different in how they are locked. If you implement an interface, you can create an implementation class, which you can then put in the thread's construction method. This ensures that a shared data is created every time.
But inheriting the thread class is a new object every time, whether it is data or anything that has its own, data, or locks. In order to guarantee the uniqueness of the data, this variable is modified with static.
Packagecom.thread.test;classWindos2extendsthread{Static intTicketnum = 100; StaticObject obj =NewObject (); @Override Public voidrun () {//TODO auto-generated Method Stub while(true) { synchronized(obj) {if(Ticketnum > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "number sold" + ticketnum--); } } } }} Public classTextWindow2extendsthread{/** * @paramargs*/ Public Static voidMain (string[] args) {Windos2 W1=NewWindos2 (); Windos2 W2=NewWindos2 (); Windos2 W3=NewWindos2 (); W1.setname ("Ticket No. 1th"); W2.setname ("Ticket No. 2nd"); W3.setname ("Ticket No. 3rd"); W1.start (); W2.start (); W3.start (); }}
Packagecom.thread.test; Public classwindow{ Public Static voidMain (string[] args) {Testwindow W=NewTestwindow (); Thread W1=NewThread (W); Thread W2=NewThread (W); Thread W3=NewThread (W); W1.setname ("One Ticket,"); W2.setname ("Ticket No. 2nd"); W3.setname ("Ticket No. 3rd"); W1.start (); W2.start (); W3.start (); }}classTestwindowImplementsrunnable{intTicketnum = 100; @Override Public voidrun () { while(true) { synchronized( This){ if(ticketnum>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Number Sold" +ticketnum--); } } } }}
2. Synchronization method
private synchronized Void show () {
}
Put the code that needs to synchronize the data in the synchronization method and call this method to achieve the effect of synchronization.
The synchronization method does not look like a lock, in fact its lock is the current object, which is this. Therefore, when inheriting the thread class, the synchronization effect is not reached.
Java multithreaded synchronization