Java thread Synchronization-synchronized

Source: Internet
Author: User
Tags ticket

  • Synchronized: Synchronization (lock), can be decorated code blocks and methods, the modified code blocks and methods once accessed by a thread, it is directly locked, other threads will not be able to access
  • The synchronous lock object of a non-static method is this
    The static method's lock synchronization object is the bytecode object of the current class
  • Mock train station ticketing case

    Synchronizing code blocks:
    public class Ticket implements Runnable {

    int tickets = 100;//总票数Object obj = new Object(); //锁对象@Overridepublic void run() {    //卖票    while (true) {        synchronized (obj) {            if (tickets > 0) {                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println(Thread.currentThread().getName() + "卖出了第" + (tickets--) + "张票");            }        }    }}

    }

    Synchronization method
    public class Ticket implements Runnable {

    int tickets = 100;//总票数Object obj = new Object(); //锁对象@Overridepublic void run() {    //卖票    while (true) {        method();    }}public synchronized void method(){    if (tickets > 0) {        try {            Thread.sleep(10);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName() + "卖出了第" + (tickets--) + "张票");    }}

    }

    Test class
    public class Tickettest {
    public static void Main (String args[]) {

        Ticket t = new Ticket();    Thread t1 = new Thread(t);    Thread t2 = new Thread(t);    Thread t3 = new Thread(t);    t1.setName("窗口1");    t2.setName("窗口2");    t3.setName("窗口3");    t1.start();    t2.start();    t3.start();}

    }

    Java thread Synchronization-synchronized

    Related Article

    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.