Effect of j2se local variables and member variables on threads

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.