Multi-thread runnable base class-sharing and exclusive of resources between threads

Source: Internet
Author: User

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

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.