Java thread and synchronization (synchronized) Sample Code
Import java. Io .*;
Import java. util .*;
Import java. Text. simpledateformat;
Public class testthread extends thread
{
Private Static integer threadcounterlock; // used for synchronization to prevent data from being written incorrectly.
Private Static int threadcount; // This class of thread counters
Static
{
Threadcount = 0;
Threadcounterlock = new INTEGER (0 );
}
Public testthread ()
{
Super ();
}
Public synchronized static void incthreadcount ()
{
Threadcount ++;
System. Out. println ("thread count after Enter:" + threadcount );
}
Public synchronized static void decthreadcount ()
{
Threadcount --;
System. Out. println ("thread count after leave:" + threadcount );
}
Public void run ()
{
Synchronized (threadcounterlock) // synchronous
{
Threadcount ++;
System. Out. println ("thread count after Enter:" + threadcount );
}
// Incthreadcount (); // It is equivalent to the preceding statement Block
Final long nsleepmillisecs = 1000; // sleep time in the loop
Long ncurrenttime = system. currenttimemillis ();
Long nendtime = ncurrenttime + 30000; // run End Time
Simpledateformat = new simpledateformat ("yyyy-mm-dd hh: mm: SS ");
Try
{
While (ncurrenttime <nendtime)
{
Ncurrenttime = system. currenttimemillis ();
System. Out. println ("Thread" + this. hashcode () + ", current time:" + simpledateformat. Format (new date (ncurrenttime )));
Try
{
Sleep (nsleepmillisecs );
}
Catch (interruptedexception ex)
{
Ex. printstacktrace ();
}
}
}
Finally
{
Synchronized (threadcounterlock) // synchronous
{
Threadcount --;
System. Out. println ("thread count after leave:" + threadcount );
}
// Decthreadcount (); // It is equivalent to the preceding statement Block
}
}
Public static void main (string [] ARGs)
{
Testthread [] testthread = new testthread [2];
For (INT I = 0; I <testthread. length; I ++)
{
Testthread [I] = new testthread ();
Testthread [I]. Start ();
}
}
}
Synchronization is simply to say that you cannot use it when I use it. This is the case if everyone uses the same thing!
For example, if an apple is delicious, I just pull it up and put it down. You just pull it up and take a bite again. This is the same. If you bite it together, haha, let's get married, this is often seen at the wedding, and you are not afraid to bite your mouth!
For example, there is now a class with a private member and an apple in the class. There are two methods for reading and eating.
I don't want to synchronize now. I just "read", haha, an apple, and I "eat" 1/4.
As soon as you look at it, haha, an apple, also "eat" 1/4.
The possible situation is that you can see an apple, but my method of eating is used before you, so you can only eat 3/4 of 1/4, that is, 3/16, instead of 1/4.
Now add the synchronization lock. When I am eating, you can see that it is locked. When it is finished, you can check it again. Ah, 3/4 apple, it's better to eat 1/3. That's it!