Data sharing in a multi-threaded range

Source: Internet
Author: User

The shared workaround reference in the multi-threaded range is 4:

1. If the thread executes the same code, the shared data is placed on the Runnable object when multiple threads share the same Runnable object

2. If multiple threads execute different code, encapsulate the shared data into an object, passing the object to each Runnable object individually

3. If multiple threads execute different code, take the shared data as the final member variable of the outer class, and take the different runnable objects as inner classes to fetch the data actively

4. How the data is declared as static ()

See the example below:

1. If the thread executes the same code, the shared data is placed on the Runnable object when multiple threads share the same Runnable object

 Public classMuiltthreadshare {/*** Multiple threads sharing Data method: * 1. If the thread executes the same code, when multiple threads share the same Runnable object, the shared data is placed in the Runnable object * 2. If multiple threads execute different code, encapsulate the shared data in an object and The elephant is passed to each Runnable object individually * 3. If multiple threads execute different code, share the data as the final member variable of the outer class, and take the different runnable objects as internal classes actively fetching the data*/         Public Static voidMain (string[] args) {//1. Mode oneTask1 Task1 =NewTask1 (); NewThread (Task1). Start (); NewThread (Task1). Start (); NewThread (Task1). Start (); }    }classTask1Implementsrunnable{/*** 1. If the thread executes the same code, the shared data is placed on the Runnable object when multiple threads share the same Runnable object*/        Private inti = 100; @Override Public voidrun () {increase ();    Decrease (); }        Private synchronized voidIncrease () {Try{Thread.Sleep (200);//to make it easier to see thread execution behavior}Catch(interruptedexception e) {e.printstacktrace (); } I++; System.out.println (Thread.CurrentThread (). GetName ()+ ", num:" +i); }    Private synchronized voiddecrease () {i--; System.out.println (Thread.CurrentThread (). GetName ()+ ", num:" +i); }

Run Result: Eventually 100, different threads use shared data

Run Results //     thread-0,num:101//    thread-2,num:102//    thread-1,num:103  //    thread-2,num:102//    thread-0,num:101//      thread-1,num:100

2. If multiple threads execute different code, encapsulate the shared data into an object, passing the object to each Runnable object individually

 Public classMuiltThreadDataShare2 { Public Static voidMain (string[] args) {//2. If multiple threads execute different code, encapsulate the shared data into an object, passing the object to each Runnable object individually        /*** Analog bank transfer function, you can specify the deposit and withdrawal amount, the initial amount of the account*/Sharedata Data=NewSharedata (0); //Save $50        NewThread (NewTaskincrease (Data, 50) . Start (); //Take 30 Yuan        NewThread (NewTaskdecrease (data, 30) . Start (); //Deposit        NewThread (NewTaskincrease (data, 20) . Start (); }}classTaskdecreaseImplementsRunnable { PublicTaskdecrease (Sharedata Sharedata,intnum) {         This. Sharedata =Sharedata;  This. num =num; }    Private intnum; PrivateSharedata Sharedata; @Override Public voidrun () {sharedata.decrease (num); }}classTaskincreaseImplementsRunnable { PublicTaskincrease (Sharedata Sharedata,intnum) {         This. Sharedata =Sharedata;  This. num =num; }    PrivateSharedata Sharedata; Private intnum; @Override Public voidrun () {sharedata.increase (num); }}classSharedata { PublicSharedata (intnum) {i=num; System.out.println ("The account is initialized with the amount:" +num); }    Private inti;  Public synchronized voidIncrease (inti) {Try{Thread.Sleep (200);//to make it easier to see thread execution behavior}Catch(interruptedexception e) {e.printstacktrace (); }         This. i = This. i +i; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Deposit" + i + "yuan, current account balance:" + This. i); }     Public synchronized voidDecrease (inti) { This. i = ThisIi; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Withdrawal" + i + "yuan, current account balance:" + This. i); }}

Operation Result:

The account is initialized, the amount is: 0thread-0 account deposited 50 yuan, the current account balance is: 2 The Account deposit 20 yuan, the current account balance is: 1thread-30 account out of The current account balance is: 40

3. If multiple threads execute different code, take the shared data as the final member variable of the outer class, and take the different runnable objects as inner classes to fetch the data actively

 Public classMuiltThreadDataShare3 { Public Static voidMain (string[] args) {FinalData data =NewData (); NewThread (NewRunnable () {@Override Public voidrun () {data.decrease (10);        }}). Start (); NewThread (NewRunnable () {@Override Public voidrun () {data.increase (30);    }}). Start (); }}classData {Private intMoney = 100;  Public intGetmoney () {returnMoney ; }     Public voidSetmoney (intMoney ) {         This. Money =Money ; }     Public synchronized voidIncrease (inti) {Try{Thread.Sleep (200);//to make it easier to see thread execution behavior}Catch(interruptedexception e) {e.printstacktrace (); }         This. Money = This. Money +i; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Deposit" + i + "yuan, current account balance:" + This. Money); }     Public synchronized voidDecrease (inti) { This. Money = This. Money-i; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Withdrawal" + i + "yuan, current account balance:" + This. Money); }}

4. How the data is declared as static

 Public classMuiltThreadDataShare4 {Private Static intnum = 100;  Public Static voidMain (string[] args) {NewThread (NewRunnable () {@Override Public voidrun () {Increase (100);        }}). Start (); NewThread (NewRunnable () {@Override Public voidRun () {Decrease (30);    }}). Start (); }     Public Static synchronized voidIncrease (inti) {Try{Thread.Sleep (200);//to make it easier to see thread execution behavior}Catch(interruptedexception e) {e.printstacktrace (); } num= num +i; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Deposit" + i + "yuan, current account balance:" +num); }     Public Static synchronized voidDecrease (inti) {num= num-i; System.out.println (Thread.CurrentThread (). GetName ()+ "Account Withdrawal" + i + "yuan, current account balance:" +num); }}

Finish

Data sharing in a multi-threaded range

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.