Java threads and happily package Util.concurrent's research (7)

xiaoxiao2021-03-06  37

Instance using ReentrantLock

1. Introduction to the example:

This example is an example of a typical multi-threaded competition: two bank staff simultaneously operate the same account. I use not any control, use ReentrantLock, and implement three ways of Synchronized and compare the results.

Second, class list:

Class name function Account Bank Account class Bank Bank Class: Define Call Action Account Transaction Method BankwithSync Bank Class: Using Synchronized Definition Call Operation Account Transactions Transaction Account Transaction Class: Definition / Deputy Operation Clerk Bank Staff Class: Using the Bank class as the parameters of the construction method, the RunNable interface is implemented, and the bank account is performed according to the type of transaction (not using the lock) ClerkwithSync Bank staff class: Use the BankWithSync class as the parameter of the constructor, implementing Runnable Interface, follow the transaction type to pay the bank account / departments Operation ClerkwithLock Bank staff class: Use the Bank class as the parameter of the constructor, implement the Runnable interface, follow the transaction type to pay the bank account / payment operation (using Reentrantlock) MulticlerkCurrentTransaction Provide three ways to invoke in the introduction to implement two bank staff while operating the same account. OperationWithunuseLock - Transaction Operation OperationWithReentrantLock-OperationWithsynchronized- transactionWithsynchronized- using the reusable lock-based transaction OperationWithsynchronized- Transaction Operations for accounts using Synchronized

The OperationWithunuSelock mainly uses: Clerk class and Bank class;

OperationWithreentrantlock mainly uses: Clerkwithlock class and Bank class.

Operationwithsynchronized mainly uses: ClerkwithSync class and BankwithSync class.

Run Results: Initial: $ 856 Bottom: $ 888 Final deposit: $ 22: $ 468 unused lock spending 6480ms Initial deposit: $ 500% of your post: $ 878 Final deposit: $ 463 should : $ 463 Using the Reentrant lock spending 6639ms Initial deposit: $ 500 Posts: $ 832 Final Deposit: $ 459: $ 459 Using Synchornized Synchronous Synchronization Take 6249ms

Third, source code:

/ *

* Account.java

*

* CREATED ON January 25, 2005, 3:15 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

/ **

* Define bank account classes

* @Author smart pig

* /

Public class account {

Private int Balance;

Private int acidnumber;

/ **

* Bank account construction method

* @Param AccountNumber User Account

* @Param balance account balance

* /

Public Account (int rt balance) {

this.accountnumber = AccountNumber;

THIS.BALANCE = Balance;

}

/ **

* Return the account balance

* @Return account balance

* /

Public int getBalance () {

Return balance;

/ **

* Assignment account balance

* @Param Balance balance

* /

Public void setbalance (int Balance) {

THIS.BALANCE = Balance;

}

/ **

* Return to the bank account

* @Return bank account

* /

Public int getaccountnumber () {

Return Accountnumber;

}

Public string toString () {

Return "No." AccountNumber ": $" Balance;

}

}

/ *

* Bank.java

*

* CREATED ON January 25, 2005, 3:54 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *;

/ **

* Bank class, main implementation

* @Author smart pig

* /

Public class bank {

/ ** Creates a new instance of bank * /

Public bank () {

}

/ **

* Perform a transaction, operate the balance of the user account according to the type of transaction.

* @Param Transaction Transaction Object

* /

Public void dotransaction (transaction transfer) {

Int balance = Transaction.getAccount (). getBalance ();

Switch (Transaction.getTransactionType ()) {

Case transaction.credit:

Try {

Thread.sleep (100);

}

Catch (InterruptedException E) {

System.out.println (e);

}

BALANCE = Transaction.getamount ();

Break;

Case transaction.debit:

Try {

Thread.sleep (150);

}

Catch (InterruptedException E) {

System.out.println (e);

}

Balance- = Transaction.getamount ();

Break;

DEFAULT:

System.out.println ("invalid transaction");

System.exit (1);

}

Transaction.getAccount (). setBalance (Balance);

}

}

/ *

* Bankwithsync.java

*

* CREATED ON January 25, 2005, 3:54 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *;

/ **

* Bank class, mainly implementing transactions (sync using Synchronized)

* @Author smart pig

* /

Public class bankwithsync {

/ ** Creates a new instance of bank * /

Public Bankwithsync () {

}

/ **

* Execute a transaction, operate the balance of the user account according to the type of transaction (synchronized using Synchronized).

* @Param Transaction Transaction Object * /

Synchronized public void dotransaction (transaction transfer) {

Int balance = Transaction.getAccount (). getBalance ();

Switch (Transaction.getTransactionType ()) {

Case transaction.credit:

Try {

Thread.sleep (100);

}

Catch (InterruptedException E) {

System.out.println (e);

}

BALANCE = Transaction.getamount ();

Break;

Case transaction.debit:

Try {

Thread.sleep (150);

}

Catch (InterruptedException E) {

System.out.println (e);

}

Balance- = Transaction.getamount ();

Break;

DEFAULT:

System.out.println ("invalid transaction");

System.exit (1);

}

Transaction.getAccount (). setBalance (Balance);

}

}

/ *

* Clerk.java

*

* Created on January 25, 2005, 4:01 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *;

/ **

* Define the bank staff class (no lock)

* @Author smart pig

* /

Public class clerk imports runnable {

PRIVATE BANK Thebank;

PRIVATETEN

/ **

* Constructing bank staff

* @Param thebank Bank class object

* /

Public Clerk (Bank thebank) {

THIS.THEBANK = Thebank;

Intray = NULL;

}

/ **

* Bank staff executes affairs

* @Param Transaction transaction class object

* /

Public void dotransaction (transaction transfer) {

Intray = Transaction;

}

/ **

* RUN method for thread

* /

Public void run () {

While (true) {

While (intRay == null) {

Try {

Thread.sleep (150);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Thebank.dotransaction (intray);

Intray = NULL;

}

}

/ **

* Return to the staff busy

* @return Returns true if the staff is busy; otherwise returns false.

* /

Public boolean isbusy () {

Return intRay! = null;

}

}

/ *

* Clerkwithlock.java

*

* Created on January 25, 2005, 4:01 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *; import edu.emory.mathcs.backport.java.util.concurrent.locks. *;

Import edu.emory.mathcs.Backport.java.util.concurrent. *;

/ **

* Define the bank staff class (using ReentrantLock)

* @Author smart pig

* /

Public Class Clerkwithlock Implements Runnable {

PRIVATE BANK Thebank;

PRIVATETEN

Private reentrantlock lock;

/ **

* Constructing bank staff

* @Param thebank Bank class object

* @Param Lock retrnile lock object

* /

Public Clerkwithlock (Bank Thebank, Reentrantlock Lock) {

THIS.THEBANK = Thebank;

THIS.LOCK = LOCK;

Intray = NULL;

}

/ **

* Bank staff execute a transaction (synchronized using ReentrantLock)

* @Param Transaction transaction class object

* /

Public void dotransaction (transaction transfer) {

Intray = Transaction;

}

/ **

* RUN method for thread

* /

Public void run () {

While (true) {

While (intRay == null) {

Try {

Thread.sleep (150);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Try {

Lock.lockInterruptibly ();

Thebank.dotransaction (intray);

Intray = NULL;

Lock.unlock ();

}

Catch (InterruptedException E) {

if (Lock.isheldbycurrentthread ()) {

Lock.unlock ();

}

System.out.println (e);

}

}

}

/ **

* Return to the staff busy

* @return Returns true if the staff is busy; otherwise returns false.

* /

Public boolean isbusy () {

Return intRay! = null;

}

}

/ *

* Clerkwithsync.java

*

* Created on January 25, 2005, 4:01 pm

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *;

/ **

* Define bank staff (Bank's transaction method using Synchronized sync)

* @Author smart pig

* /

Public Class Clerkwithsync IMPLEMENTS Runnable {

PRIVATE BANKWITHSYNC Thebank

PRIVATETEN

/ **

* Constructing bank staff (Bank's transaction method uses Synchronized sync)

* @Param thebank Bank class object

* /

Public ClerkwithSync (Bankwithsync thebank) {this.thebank = thebank;

Intray = NULL;

}

/ **

* Bank staff executes affairs

* @Param Transaction transaction class object

* /

Public void dotransaction (transaction transfer) {

Intray = Transaction;

}

/ **

* RUN method for thread

* /

Public void run () {

While (true) {

While (intRay == null) {

Try {

Thread.sleep (150);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Thebank.dotransaction (intray);

Intray = NULL;

}

}

/ **

* Return to the staff busy

* @return Returns true if the staff is busy; otherwise returns false.

* /

Public boolean isbusy () {

Return intRay! = null;

}

}

/ *

* Transaction.java

*

* CREATED ON January 25, 2005, 3:13 in the afternoon

* /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

/ **

* Bank transaction

* @Author smart pig

* /

Public class transaction {

Public static final int debits = 0;

Public static final int current = 1;

Public static string [] types = {"debit", "credit"};

PRIVATE ACCOUNT;

PRIVATE INT AMOUNT;

PRIVATE INT TransactionsType;

/ **

* Configuration method of transaction

* @Param Account Bank Account

* @Param TransactionType transaction type (%)

* @Param Amount account / payment amount

* /

Public Transaction (Account Account, Int TransactionsType, Int Amount) {

THIS.ACCOUNT = Account;

THIS.TRANSACTIONTYPE = TransactionsType;

THIS.AMOUNT = Amount;

}

/ **

* Return to the user account class

* @Return User Account Class

* /

Public Account getaccount () {

Return Accent;

}

/ **

* Return to transaction type

* @Return transaction type string

* /

Public int GetTransactionType () {

Return TransactionType;

}

/ **

* Return to the operating amount

* @return operation amount

* /

Public int getamount () {

Return Amount;

}

Public string toString () {

Return Types [TransactionType] ":" ": $" Amount;

}

}

/ *

* MulticlerkConcurrentTransaction.java

*

* CREATED ON January 25, 2005, 4: 10 * /

Package bjinfotech.util.threadManage.concurrent.tryit.bank;

Import bjinfotech.util.threadManage.concurrent.tryit.bank. *;

Import edu.emory.mathcs.Backport.java.util.concurrent.locks. *;

Import java.util.random;

/ **

* Multiple bank staff concurrently visited the same bank account

* @Author smart pig

* /

Public class multiclerkconcurrenttransaction {

/ ** Creates a new instance of multiclerkconcurrentTransaction * /

Public multiclerkconcurrenttransaction () {

}

/ **

* Transaction operations that do not use locks

* /

Public static void Operationwithunuselock () {

INT INITIALBALANCE = 500;

INT TOTALCREDITS = 0;

INT TOTALDEBITS = 0;

Int TransactionCount = 20;

Bank thebank = new bank ();

Clerk Clerk1 = New Clerk (Thebank);

Clerk Clerk2 = New Clerk (Thebank);

Account Account = New Account (1, Initialbalance);

Thread Clerk1thread = New Thread (Clerk1);

Thread Clerk2thread = New Thread (Clerk2);

Clerk1thread.SetDaemon (TRUE);

Clerk2thread.setdaemon (TRUE);

Clerk1thread.start ();

Clerk2thread.start ();

Random Rand = new random ();

Transaction Transaction;

INT AMOUNT = 0;

// Staff 1 and staff 2 for 20 transaction operations

For (INT i = 1; i <= Transactioncount; i ) {

// Staff 1 accounts AMOUNT Yuan

Transaction = New Transaction (Account, Transaction.credit, Amount);

Totalcredits = Amount;

While (Clerk1.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Clerk1.dotiaSAction (Transaction);

// Staff 2 payment AMOUNT Yuan

Amount = 30 rand.nextint (31);

Transaction = New Transaction (Account, Transaction.debit, Amount);

TotalDebits = Amount;

While (Clerk2.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Clerk2.dotiaSAction (Transaction);

}

// Waiting for the end of the two staff work

While (Clerk1.isbusy () || Clerk2.isbusy ()) {TRY {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

// Print results

System.out.println (

"Initial deposit: $" InitialBalance "/ N"

"Accounting amount: $" Totalcredits "/ N"

"Bottomment amount: $" Totaldebits "/ N"

"Final deposit: $" Account.getBalance () "/ n"

"Should be: $" (InitialBalance Totalcredits-Totaldebits);

}

/ **

* Transaction operations with reusable locks

* /

Public static void OperationwithReentrantLock () {

INT INITIALBALANCE = 500;

INT TOTALCREDITS = 0;

INT TOTALDEBITS = 0;

Int TransactionCount = 20;

Reentrantlock Lock = New Reentrantlock ();

Bank thebank = new bank ();

Clerkwithlock Clerk1 = New Clerkwithlock (Thebank, Lock);

Clerkwithlock Clerk2 = New Clerkwithlock (Thebank, Lock);

Account Account = New Account (1, Initialbalance);

Thread Clerk1thread = New Thread (Clerk1);

Thread Clerk2thread = New Thread (Clerk2);

Clerk1thread.SetDaemon (TRUE);

Clerk2thread.setdaemon (TRUE);

Clerk1thread.start ();

Clerk2thread.start ();

Random Rand = new random ();

Transaction Transaction;

INT AMOUNT = 0;

// Staff 1 and staff 2 for 20 transaction operations

For (INT i = 1; i <= Transactioncount; i ) {

// Staff 1 accounts AMOUNT Yuan

Transaction = New Transaction (Account, Transaction.credit, Amount);

Totalcredits = Amount;

While (Clerk1.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Clerk1.dotiaSAction (Transaction);

// Staff 2 payment AMOUNT Yuan

Amount = 30 rand.nextint (31);

Transaction = New Transaction (Account, Transaction.debit, Amount);

TotalDebits = Amount;

While (Clerk2.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {system.out.println (e);

}

}

Clerk2.dotiaSAction (Transaction);

}

// Waiting for the end of the two staff work

While (Clerk1.Isbusy () || Clerk2.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

// Print results

System.out.println (

"Initial deposit: $" InitialBalance "/ N"

"Accounting amount: $" Totalcredits "/ N"

"Bottomment amount: $" Totaldebits "/ N"

"Final deposit: $" Account.getBalance () "/ n"

"Should be: $" (InitialBalance Totalcredits-Totaldebits);

}

/ **

* Transaction operations with Synchronized accounts

* /

Public static void Operationwithsynchronized () {

INT INITIALBALANCE = 500;

INT TOTALCREDITS = 0;

INT TOTALDEBITS = 0;

Int TransactionCount = 20;

Bankwithsync thebank = new bankwithsync ();

Clerkwithsync Clerk1 = New Clerkwithsync (Thebank);

Clerkwithsync Clerk2 = New Clerkwithsync (Thebank);

Account Account = New Account (1, Initialbalance);

Thread Clerk1thread = New Thread (Clerk1);

Thread Clerk2thread = New Thread (Clerk2);

Clerk1thread.SetDaemon (TRUE);

Clerk2thread.setdaemon (TRUE);

Clerk1thread.start ();

Clerk2thread.start ();

Random Rand = new random ();

Transaction Transaction;

INT AMOUNT = 0;

// Staff 1 and staff 2 for 20 transaction operations

For (INT i = 1; i <= Transactioncount; i ) {

// Staff 1 accounts AMOUNT Yuan

Transaction = New Transaction (Account, Transaction.credit, Amount);

Totalcredits = Amount;

While (Clerk1.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Clerk1.dotiaSAction (Transaction);

// Staff 2 payment AMOUNT Yuan

Amount = 30 rand.nextint (31);

Transaction = New Transaction (Account, Transaction.debit, Amount);

Totaldebits = Amount; While (Clerk2.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

Clerk2.dotiaSAction (Transaction);

}

// Waiting for the end of the two staff work

While (Clerk1.Isbusy () || Clerk2.isbusy ()) {

Try {

Thread.sleep (25);

}

Catch (InterruptedException E) {

System.out.println (e);

}

}

// Print results

System.out.println (

"Initial deposit: $" InitialBalance "/ N"

"Accounting amount: $" Totalcredits "/ N"

"Bottomment amount: $" Totaldebits "/ N"

"Final deposit: $" Account.getBalance () "/ n"

"Should be: $" (InitialBalance Totalcredits-Totaldebits);

}

Public static void main (string [] argv) {

Operationwithunuselock ();

OperationwithReentrantLock ();

Operationwithsynchronized ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-64538.html

New Post(0)