JAVA -- thread synchronization, java -- thread
Following the thread introduction yesterday, I have summarized the synchronization problem in the thread today. Now I will discuss it with you.
What is the use of thread locking? For example, if you have 30000 oceans in the bank, and now you get the money from the bank, after entering the password, you have already entered the withdrawal amount. For example, if you entered 20000, at the moment when the bank gives you money, your wife also goes to the bank to get the money. Your wife also gets 20000, because at this time your account is still 30000, therefore, the Bank has performed the same operation on your wife's side. In this way, after the two of you have completed their respective operations, your account recorded by the Bank should also have 10000 deposits, is it so nice. To solve this problem, we will use the thread lock knowledge. Let's take a look at it.
1. Example of unprocessed thread synchronization:
Public class TextSync implements Runnable {/** unprocessed thread synchronization * @ param args */Time time = new Time (); public static void main (String [] args) {TextSync text = new TextSync (); Thread t1 = new Thread (text); Thread t2 = new Thread (text); t1.setName ("t1 "); t2.setName ("t2"); t1.start (); t2.start () ;}@ Override public void run () {time. add (Thread. currentThread (). getName () ;}} class Time {private static int num = 0; public void add (String name) {try {num ++; // when the first thread is executed, num becomes 1 and the first thread is paused for one second, // The second thread starts execution. When the second thread is executed till now, num is changed to 2, and the second thread is paused for one second. // at this time, num is also changed to 2, so the final result is 2; Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (name + "is the" + num + "execution thread. ");}}
Output result:
Ii. Thread Synchronization
Public class TextSynctwo implements Runnable {/** thread synchronization * @ param args */Time1 time = new Time1 (); public static void main (String [] args) {TextSynctwo text = new TextSynctwo (); Thread t1 = new Thread (text); Thread t2 = new Thread (text); t1.setName ("t1 "); t2.setName ("t2"); t1.start (); t2.start () ;}@ Override public void run () {time. add (Thread. currentThread (). getName () ;}} class Time1 {private stati C int num = 0; // synchronized locks the current thread, which can be declared during method definition or set in method. Public synchronized void add (String name) {// synchronized (this) {// lock the current Thread to prevent other threads from executing try {num ++; Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (name + "is the" + num + "execution thread. ");//}}}
Output result:
3. deadlock
Public class TestDeadLock implements Runnable {/** deadlock * @ param args */private int flag = 0; static Object o1 = new Object (); static Object o2 = new Object (); public static void main (String [] args) {TestDeadLock td1 = new TestDeadLock (); TestDeadLock td2 = new TestDeadLock (); td1.flag = 1; td2.flag = 2; thread t1 = new Thread (td1); Thread t2 = new Thread (td2); t1.setName ("t1"); t2.setName ("t2"); t1.start (); t2.start () ;}@ Override public void run () {System. out. println (Thread. currentThread (). getName (); if (flag = 1) {synchronized (o1) {try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o2) {System. out. println ("1") ;}}if (flag = 2) {synchronized (o2) {try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o1) {System. out. println ("2 ");}}}}}
Iv. Locking
Public class TT implements Runnable {/** locked * @ param args */int B = 100; public static void main (String [] args) {TT tt = new TT (); thread th = new Thread (tt); th. start (); try {tt. m2 ();} catch (Exception e) {e. printStackTrace ();} System. out. println (tt. b) ;}@ Override public void run () {try {m1 () ;}catch (Exception e) {e. printStackTrace () ;}} private synchronized void m1 () throws Exception {B = 1000; Thread. sleep (1, 5000); System. out. println ("B =" + B);} private synchronized void m2 () throws Exception {Thread. sleep (2500); B = 2500 ;}}
I have a question about locking this. I hope you can give me some advice. The output is as follows:
What I want to ask is what m2 is executed first. m1 can be executed only after m2 is executed.
Thank you for your reply.
Java thread synchronization problems
The requirement is not clear enough. I cannot understand your code design, but some obvious problems are as follows:
Why do you use synchronized for Thread run? The mutex of the synchronized synchronization method only occurs when multiple threads call methods of the same object. Here, the run method of each thread is enabled by the main thread. Why do multiple threads call run?
In addition, calling wait (); and policyall within the thread is equivalent to calling self. wait and self. notifyAll, the two methods are synchronized through the same object for mutual exclusion, so the respective threads use their own mutual exclusion, there is no intersection between threads, how does one implement interaction? For example, thread t1 calls wait () and enters its own waiting zone. It can no longer run, and other threads are waiting to call t1.policyall for activation, but thread t2 and t3 do not know the T1. how can we activate it? It is even possible that both t2 and t3 have entered the waiting area of their own objects and are difficult to protect themselves. In this way, no one can save anyone ~~
Assume your thinking: 140 customers, each of which needs to be handled at a specific time. There are a total of 12 windows for handling customers, after each window is processed, process the next customer (the operation time of each window does not affect the operation of other windows) until all the operations are completed. This is a problem of producers and consumers. The producers here are the customers and their time, and there is a fixed amount. Consumers are the windows. We abstract them into threads, so:
Abstract A Routine class to indicate a transaction, which describes the user name and the time the user needs to process:
Class Routine {
String name;
Long orderTime;
Int custNumber; // The number of the current customer.
}
Abstract A Routine Provider class to provide transactions to the window. You need to consider synchronization:
Class RoutineProvider {
Private List <Routine> routines = new route List <Routine> ();
Public void init (){
// Initialize here to add 140 instances for routines, and set count to 140
}
// Declare fetchRoutine to provide a Routine to the window thread. Note that synchronization is required here.
Public synchronized Routine fetchRoutine (){
If (routines. isEmpty () return null;
Return routines. removeFirst ();
}
}
Next is the window thread class:
Class WorkThread extends Thread {
Private RoutineProvider provider;
Private String name;
Public WorkThread (String name, RoutineProvider provider ){
This. name = name;
This. provider = provider;
}
Public void run (){
While (true ){
Routine r = provider... the remaining full text>
How to generate alternate output for java Thread Synchronization
Public class change implements Runnable {
Private String SC, xf;
Private int count;
Private boolean flag = false;
Private int I; // loop I times
Public change (String a, String B, int I ){
SC =;
Xf = B;
This. I = I;
}
Public void run (){
While (count <I)
Changenumber ();
}
Public synchronized void changenumber (){
If (Thread. currentThread (). getName (). equals (SC )){
Try {
If (flag)
Wait ();
Else if (count <I ){
Flag = true;
System. out. println (Thread. currentThread (). getName ()
+ ": The producer produces goods" + count );
Notify ();
Thread. sleep (1000 );
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
Else if (Thread. currentThread (). getName (). equals (xf )){
Try {
If (flag & count <I ){
Flag = false;
System. out. println (Thread. currentThread (). getName ()
+ ": The consumer consumes goods" + (count ++ ));
Notify ();
Thread. sleep (1000 );
} Else
Wait ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
Public static void main (String args []) {
String a = "producer ";
String B = "consumer ";
Change c = new change (a, B, 10 );
Thread scz = new Thread (c );
Thread xfz = new Thread (c );
Scz. setName ();
Xfz. setName (B );
Scz. start ();
Xfz. start ();
}
}... Remaining full text>