Java multi-thread synchronous synchronized and asynchronous ynchronized

Source: Internet
Author: User

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

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.