Java multi-thread synchronous synchronized and asynchronous ynchronized
A single thread is secure, because there is only one thread, and no threads can snatch the same resource.
Code example:
Public class SingleThread {int num = 10; public void add () {while (num <13) {num ++; try {Thread. sleep (1000);} catch (Exception e) {System. out. println ("interrupted");} System. out. println (num) ;}} public static void main (String [] args) {Thread thread = Thread. currentThread (); // get the currently running thread object thread. setName ("single thread"); // rename the System thread. out. println (thread. getName () + "running"); SingleThread st = new SingleThread (); st. add ();}}
Multi-thread security, synchronized Synchronous Code Block
Synchronized (object) {}; // Synchronous Code Block
Synchronized returned value method name () {}; // synchronous method
Class One {int num = 10; public void add () {synchronized (this) {// Synchronous Code block. The synchronous method can also achieve synchronized void add (){}; num ++; try {Thread. sleep (1000);} catch (InterruptedException e) {System. out. println ("interrupted");} System. out. println (num) ;}} class Two implements Runnable {One one = new One (); @ Override public void run () {one. add (); // call the add method} public class Synch {public static void main (String [] args) {Two two = new Two (); thread t1 = new Thread (two); // create three subthreads Thread t2 = new Thread (two); Thread t3 = new Thread (two); t1.start (); t2.start (); t3.start ();}}
Note: Observe the differences between running results for removing the synchronized keyword!
Normal running result:
11
12
13