When writing a class, if the code in that class might run in a multithreaded environment, consider the problem of synchronization. The language-level synchronization primitives--synchronized are built into Java, which greatly simplifies the use of multithreaded synchronization in Java. We first write a very simple multithreaded program, is to simulate a bank of multiple threads at the same time to the same savings account deposit, withdrawal operations.
In the program we use a simplified version of the account class that represents the information for a bank. In the main program we first generated 1000 threads, then started them, each thread to John's account to save 100 yuan, and then immediately take out 100 yuan. So, for John's account, the balance of the final account should be 1000 yuan. However, the results of the operation are beyond our imagination, first of all to look at our demo code:
Class Account
{
String name; float amount;
Public account (String name, float amount)
{
THIS.name = name;
This.amount = amount;
}
public void deposit (float amt)
{
float tmp = amount;
TMP = = AMT;
Try
{
Thread.Sleep (100);
Simulate the time required for other processing, such as refreshing the database
}
catch (Interruptedexception e)
{
Ignore
}
Amount = tmp;
}
public void Withdraw (float amt)
{
float tmp = amount;
TMP-= AMT;
Try
{
Thread.Sleep (100);
Simulate the time required for other processing, such as refreshing the database
}
catch (Interruptedexception e)
{
Ignore
}
Amount = tmp;
}
public float getbalance ()
{
return amount;
}
}
public class Accounttest
{
private static int num_of_thread = 1000;
Static thread[] threads = new Thread[num_of_thread];
public static void Main (string[] args)
{
Final Account ACC = new Account ("John", 1000.0f);
for (int i = 0; i< num_of_thread; i++)
{
Threads[i] = new Thread (New Runnable ()
{
public void Run ()
{
Acc.deposit (100.0f);
Acc.withdraw (100.0f);
}
}
);
Threads[i].start ();
}
for (int i=0; i<num_of_thread; i++)
{
try {threads[i].join ();
Wait for all threads to run to the end
}
catch (Interruptedexception e)
{
Ignore
}
}
System.out.println ("Finally, John's balance is:" + acc.getbalance ());}