Between multiple threads generated from an object of a runnable subclass,
The member variables and member methods of this object are shared.
Only the local variables in the run () method and run method are exclusive.
You can use the synchronized keyword to resolve access conflicts between shared resources.
For example, if there is a ticket selling problem in the train window, 100 tickets must be sold in four windows.
Package thread1;
Public class threadt {
Public static void main (string [] ARGs ){
Threadtest A = new threadtest ();
Thread TT = new thread ();
TT. Start ();
Thread T1 = new thread ();
T1.start ();
Thread t2 = new thread ();
T2.start ();
Thread T3 = new thread ();
T3.start ();
}
}
Class threadtest implements runnable {
Private int I = 100;
Public void run (){
While (true ){
If (I> 0 ){
System. Out. println (thread. currentthread (). getname () + "ticket selling" + I --);
Sale ();
}
}
}
The output result of this example may be sold with two tickets numbered 100. For security and rigor, the synchronized method is required, that is, synchronization.
You can use the synchronization method or the code block to synchronize data.
The code is changed to the following:
Class threadtest implements runnable {
Private int I = 100;
Public void run (){
While (true ){
/* If (I> 0 ){
System. Out. println (thread. currentthread (). getname () + "ticket selling" + I --);*/
Sale ();
}
}
Public synchronized void sale (){
If (I> 0 ){
System. Out. println (thread. currentthread (). getname () + "ticket selling" + I --);
}
}
For more information, see.
Source: http://blog.csdn.net/wangyunhe1/article/details/7947416