Java multithreaded operations the same variable

Source: Internet
Author: User

example, suppose to be a ticket-selling system, where multiple threads (2 threads in an example) manipulate the same variable Ticketcount (number of remaining votes).

Expected: Multiple threads synchronize to the same variable without causing confusion.

public class Test implements Runnable {

Private String ThreadName;
private int ticketcount;

Public Test (String threadname, int ticketcount) {
This.threadname = ThreadName;
This.ticketcount = Ticketcount;
}

public synchronized int Sellticket () {
return ticketcount--;
}

@Override
public void Run () {
TODO auto-generated Method Stub
while (Ticketcount > 0) {
System.out.println (Getthreadname () + ":" + sellticket ());
}
}

Public String Getthreadname () {
Thread a = Thread.CurrentThread ();
return A.getname ();
}

public static void Main (string[] args) {
Test T1 = new Test ("Ticket available", 10);
Thread thread1 = new Thread (t1,
"1 window Sell ticket, ticket available");
Thread thread2 = new Thread (t1,
"2 window Sell ticket, ticket available");
Thread1.start ();
Thread2.start ();
}

}

----------------------Print results (different every time)----------------------

2 window Sell ticket, ticket Available:9
2 window Sell ticket, ticket Available:8
2 window Sell ticket, ticket Available:7
2 window Sell ticket, ticket available:6
2 window Sell ticket, ticket Available:5
2 window Sell ticket, ticket Available:4
1 window Sell ticket, ticket available:10
2 window Sell ticket, ticket Available:3
1 window Sell ticket, ticket available:2
2 window Sell ticket, ticket available:1

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.