Synchronized ()
Thread-safety issues sometimes occur when threads are running
For example: Ticket purchase process, there may be different window to buy the same number of tickets
Run the following code:
public class Runable implements Runnable {///Here the variable is defined as a variable of an object, when the run () function calls a different thread calls int i=1; @Overridepublic void Run () {while (true) {//output current thread name and number of votes System.out.println (Thread.CurrentThread (). GetName () +i); i++;//current thread discards CPU, re-competes resource Thread.yield (); if (i >100) Break;}}}
public class Main {public static void main (string[] args) throws Interruptedexception {//Implement Interface runable ra=new runable ();//Generate Thread object, and the interface object as the parameter thread t1=new thread (RA); Thread t2=new thread (RA);//Set name T1.setname ("Thread One") for two threads, T2.setname ("Thread Two");//Start thread T1.start (); T2.start ();}}
The following conditions can occur:
Processing method: Join the thread lock
public class Runable implements Runnable {///Here the variable is defined as a variable of an object, when the run () function calls a different thread calls int i=1; @Overridepublic void Run () {// Join the process lock, the lock is this object, before this object releases the CPU, all the code containing the process lock can not run synchronized (this) {while (true) {// Outputs the current thread name and number of votes System.out.println (Thread.CurrentThread (). GetName () +i), i++;//the current thread abandons the CPU, re-competes the resource Thread.yield (), if (i >100) Break;}}}
Java Thread Control security