First look at the example:
Public class threadtest3_zhongyao {
Public static void main (string [] ARGs ){
Runnable r = new mythread ();
Thread T1 = new thread (R );
Thread t2 = new thread (R );
T1.start ();
T2.start ();
}
}
Class mythread implements runnable {
// Int I;
@ Override
Public void run (){
Int I = 0;
While (true ){
System. Out. println ("Number" + I ++ );
Try {
Thread. Sleep (long) (1000 * Math. Random ()));
} Catch (interruptedexception e ){
E. printstacktrace ();
}
If (I = 50 ){
Break;
}
}
}
}
When I is a member variable, executeProgramPrint 50 numbers, 0 ~ 49. When I is a local variable, print 100.
If a variable is a member variable. When multiple threads operate on the member variables of the same object, they affect each other on the member variables (that is, the change of a thread to the member variables will affect another thread ). If a variable is a local variable, each thread will have a copy of the local variable. changes made to this local variable by one thread will not affect other threads.