Home > Back-end >  JAVA threads in the problem
JAVA threads in the problem

Time:11-08

Public class TT implements Runnable {
Int b=100;

Public synchronized void (m1) throws the Exception {
B=1000;
Thread.sleep (5000);
System.out.println("b=" + b);
}

Public synchronized void m2 () throws the Exception {
Thread.sleep (2500);
B=2000;
}

Public void the run () {
Try {
(m1);
} the catch (Exception e) {
e.printStackTrace();
}
}

Public static void main (String [] args) throws the Exception {
TT TT=new (TT);
Thread t=new Thread (tt);
t.start();
Tt. M2 ();
System. The out. Println (tt. B);
}
[code=Java]}
 

[/code]
Want to ask why the t.s tart (where) on the thread doesn't lock the execution m1 () but to perform in the main function of tt. M2 m2 () () and then lock the implementation,

CodePudding user response:

Start does not guarantee that the thread will be able to start immediately (thread startup is random)
You can be in tt. Additional Thread before m2. Sleep to the main line and so on for a while, to ensure that t start to call again after tt. M2

CodePudding user response:

reference 1st floor qybao response:
start does not guarantee that the thread must be able to start immediately (thread startup is random)
You can be in tt. Additional Thread before m2. Sleep to the main line and so on for a while, in order to make sure t start to call again after tt. M2

First thank you for your answer, this is I tried to start a thread,
Without sleep, every time is to lock the m2 will lock first m1. Still I tried the number of too little

CodePudding user response:

Do you like me to write will get the results you expect, do you want to pitch m1 and m2
 
Public static void main (String [] args) throws the Exception {
TT TT=new (TT);
Thread t=new Thread (tt);
t.start();
T.j oin ();
Tt. M2 ();
System. The out. Println (tt. B);
}

CodePudding user response:

It should be test number is too little, did not reflect the randomness of
You can use a while loop test more about
While (true) {
TT TT=new (TT);
Thread t=new Thread (tt);
t.start();
Tt. M2 ();
System. The out. Println (tt. B);
If (tt) b==2000) break;//if the m2 after call will exit the loop
}

CodePudding user response:

reference KeepSayingNo reply: 3/f
do you like me write will get the results you expect, do you want to pitch m1 and m2
 
Public static void main (String [] args) throws the Exception {
TT TT=new (TT);
Thread t=new Thread (tt);
t.start();
T.j oin ();
Tt. M2 ();
System. The out. Println (tt. B);
}

Thank you every time I just want to know why try is called m2 first

CodePudding user response:

reference 4 floor qybao response:
that should be test number is too little, did not reflect the randomness of
You can use a while loop test more about
While (true) {
TT TT=new (TT);
Thread t=new Thread (tt);
t.start();
Tt. M2 ();
System. The out. Println (tt. B);
If (tt) b==2000) break;//if the m2 after call will exit the loop
}

Wait a good try
  • Related