Java multi-thread synchronous asynchronous preliminary

Source: Internet
Author: User

The previous articles have learned how to use Java multithreading. In actual use, two different threads need to access the same resource, for example, when people from all over the country buy the same train ticket on 12306, the ticket seller must ensure that so many people who send a ticket request almost at the same time receive consecutive and different tickets, this requires multi-thread synchronization and Asynchronization.

I. asynchronous and asynchronous modes are easy to use. You can add the modifier synchronized before the key data operation method. When different threads call the synchronized modification method to access the same resource, only one thread is using this resource. Other threads can access this resource only after the resource is released after the thread is used up. Therefore, the thread access is dedicated. For example, when you go to the bathroom, each person occupies a private room and can only go in after others use it. Without the synchronized modifier, you can buy food at a certain stall in the food market, the stall owner has five tomatoes. At the beginning, you (representing thread a) bought the five tomatoes at a favorable price, but suddenly a thief was inserted in the middle (representing thread B) I stole two tomatoes. Your expected output is 5, but the actual output is 3. This is a problem that occurs frequently when multiple threads share resources.

2. synchronous and asynchronous methods are relatively passive. Calling the sleep () method also occupies system resources, while synchronizing the wait () and Policy () methods in the object class to solve sharing conflicts, these two methods are inherited by all objects in Java, so Java naturally supports synchronization.

The following code is pasted as an example: there are two threads: parent thread and student thread. They share a bank account. At first, the bank account has 0 funds, and the student checks the account every 2 seconds, if the account funds are not 0, 50 is taken out, and the parent checks once every 12 s. If the account funds are 0, the deposit is 200. In addition to limiting the getmoney () and savemoney () Methods of the account class to synchronized, the wait () and Policy () methods are used to notify each other. The Code is as follows:

// Accout. javapublic class accout {public int money; Public accout () {money = 0;} public synchronized void savemoney () {system. Out. println ("prepare to save money! "); Try {If (money! = 0) {system. Out. printf ("the account still has a balance! "); Y (); // reminder to save wait ();} else {money = 200; system. out. println ("saved:" + money) ;}} catch (exception e) {}} public synchronized void getmoney () {system. out. println ("Get the money! "); Try {If (money = 0) {system. out. println ("zero account balance"); wait () ;}else {money-= 50; system. out. println ("Fetch: 50 balance:" + money); Policy (); // reminder to get the money} catch (exception e ){}}}

//ParentThread.javapublic class ParentThread extends Thread{Accout act;public ParentThread (Accout act) {this.act = act;start();}public void run() {try {while(true) {Thread.sleep(12000);act.saveMoney();}}catch(Exception e) {}}}

//StudentThread.javapublic class StudentThread extends Thread{Accout act;public StudentThread (Accout act) {this.act = act;start();}public void run() {try {while (true) {Thread.sleep(2000);act.getMoney();}}catch(Exception e) {}}}

/*** Testmulthread. java * @ author Avery Liu * test multi-thread access conflict */public class testmulthread {public static void main (string [] ARGs) {accout act = new accout (); studentthread ST = new studentthread (ACT); parentthread Pt = new parentthread (ACT );}}

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.