Java thread and synchronization (Synchronized sample code

xiaoxiao2021-03-06  89

http://blog.9cbs.net/duoshanx/archive/2004/08/25/84819.aspx

Import java.io. *; import java.util. *; import java.text.SIMPLEDATEFORMAT;

Public Class Testthread Extends Thread {Private Static Integer ThreadCounterlock; // Used to synchronize, prevent data from being written in private static int threadCount; // This class thread counter

Static {threadcount = 0; threadCounterlock = new integer (0);

Public Testthread () {super ();

Public synchronized static void incountcount () {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) / / Synchronization {ThreadCount ; System.out.println ("Thread Count After ENTER: ThreadCount);}

// incthreadcount (); // and the above statement block is equivalent

Final long nsleepmillisecs = 1000; // Sleep time in the loop

Long ncurrenttime = system.currenttime = system.currenttimemillis (); long name = ncurrenttime 30000; // Run deadline SimpleDateFormat SimpleDateFormat = New SimpleDateFormat ("YYYY-MM-DD HH: MM: SS");

try {while (nCurrentTime

try {sleep (nSleepMilliSecs);} catch (InterruptedException ex) {ex.printStackTrace ();}}} finally {synchronized (threadCounterLock) // synchronous {threadCount--; System.out.println ( "thread count after leave:" threadcount);} // DecthreadCount (); // and the above statement block is equivalent}}

Public static void main (string [] args) {testthread = new testthread [2]; for (int i = 0; i

Synchronization is simply saying that you can't use it, you use it as if you use it! For example, there is only apple that is very delicious. I pulled up and put it down. You pulled up again. This is synchronized. If you bite together, huh, then you will get married, you can see this in the wedding, Not afraid, biting your mouth, hehe!

For example, there is a class, there is a private member in the class, one apple, two ways, one to eat. Now don't sync, I am "see", haha, an apple, I "eat" one quarter, you "see", haha, an apple, and "eat" quarter. The possible situation is to see an apple but my way of eating is used before you, so you may only eat 3/4 of 1/4 is 3/16 rather than 1/4 apple. Now join the synchronous lock, I am watching the lock when I am eating, wait until you have finished eating, you can see, ah 3/4 apples, eat 1/3, just like this!

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

New Post(0)