The use of Java multi-threaded-lock locks, as well as the realization of producers and consumers __java

Source: Internet
Author: User
Tags ticket

This article will mainly introduce the use of lock lock object based on Java multithreaded programming and how to realize the producer and consumer of Java code step-by-step.

1. How to use lock lock and deadlock problem description in Java
2, Java to achieve the producer and consumer process (step-by-Step optimization steps)

1. How to use lock lock and deadlock problem description in Java
Lock lock Appearance: In order to more clearly express how to lock and release the lock, JDK5 later provided a new lock object lock;
The most important method in lock Lock:
void Lock ()
void unlock ()
The following is the lock lock a simple demo demo, after the deadlock problem will also use lock lock to perform;

1 Example one: Use lock object to realize ticketing mechanism:

Sellticket.java

Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;

public class Sellticket implements Runnable {

    //definition ticket
    private int tickets =;

    Define lock object
    private Lock lock = new Reentrantlock ();

    @Override public
    Void Run () {while
        (Tickets > 0) {
            //is not with catch because it guarantees the release of the lock in case of error
            try{
                //Lock
                Lock.lock ();

                if (Tickets > 0) {
                    try {
                        thread.sleep;
                    } catch (Interruptedexception e) {
                        e.printstacktrace ();
                    }

                    System.out.println (Thread.CurrentThread (). GetName () + "selling First" + tickets--+ "Ticket");
                }
            finally {
                //release lock
                Lock.unlock ();
            }
    }}

Sellticketdemo.java

public class Sellticketdemo {public

    static void Main (string[] args) {

        //Create resource object
        Sellticket st = new Sellticke T ();

        Create window
        Thread thread1 = new Thread (ST, "window One");
        Thread thread2 = new Thread (ST, "window Two");
        Thread thread3 = new Thread (ST, "Window III");

        Open thread
        thread1.start ();
        Thread2.start ();
        Thread3.start ();
    }   

Operation Effect:

You can see that when the thread is running, it is basically a piece of work, and there is no better cross running

2 Example two: Using lock to implement deadlock mechanism

Mylock.java

/**
 * Create two locks can be directly called
 * @author YQ
 * * */public
class MyLock {
    //Create two Lock objects public
    static Final Object Obja = new Object ();
    public static final Object OBJB = new Object ();
}

Dielock.java

public class Dielock extends Thread {

    private boolean flag;

    Public Dielock (Boolean flag) {
        This.flag = flag;
    }

    @Override public
    Void Run () {
        if (flag) {
            synchronized (mylock.obja) {
                System.out.println ("if Obja"); C9/>synchronized (MYLOCK.OBJB) {
                    System.out.println ("if OBJB");}}}
        else {
            synchronized ( MYLOCK.OBJB) {
                System.out.println ("Else OBJB");
                Synchronized (mylock.obja) {
                    System.out.println (' else Obja ');}}}

Dielockdemo.java

/**
 * Synchronization disadvantage:
 *  A: Low efficiency
 *  B: Easy to produce deadlock
 * Deadlock:
 *  two or more threads in contention for resources, a phenomenon of waiting for each other
 Author YQ
 *
/public class Dielockdemo {public
    static void Main (string[] args) {
        Dielock dieLock1 = new Dielock (true);
        Dielock DieLock2 = new Dielock (false);
        Dielock1.start ();
        Dielock2.start ();
    }

Operation Effect:

2, Java to achieve the producer and consumer process (step-by-Step optimization steps)

1 The initial implementation, define a student JavaBean class, then save the student data as the producer through the set, then take out the student data as the consumer, but the following implementations are only once.
Student.java

public class Student {

    private String name;
    private int age;

    Public String GetName () {return
        name;
    }
    public void SetName (String name) {
        this.name = name;
    }
    public int getage () {return age
        ;
    }
    public void Setage (int age) {
        this.age = age;
    }

    @Override public
    String toString () {return
        "Student [name=" + name + ", age=" + Age + "]";
    }

}

Setthread.java

public class Setthread extends thread{

    private Student Student;

    Public Setthread (Student Student) {
        super ();
        This.student = student;
    }

    @Override public
    Void Run () {
        student.setname ("admin");
        Student.setage ();
    }

Getthread.java

public class GetThread extends Thread {

    private Student Student;

    Public GetThread (Student Student) {
        super ();
        This.student = student;
    }

    @Override public
    Void Run () {
        System.out.println (student.getname () + "= =" + student.getage ());
    }

Studentdemo.java

public class Studentdemo {public

    static void Main (string[] args) {

        //create shared resources for two threads
        Student Student = new St Udent ();
        Create producer and Consumer
        setthread thread1 = new Setthread (student);
        GetThread thread2 = new GetThread (student);

        Open the producer and consumer thread
        Thread1.start ();
        Thread2.start ();
    }

Operation Effect:

2 A further cycle to achieve multiple production multiple consumption, the use of synchronized mode
Student.java code ditto.

Getthread.java

public class GetThread extends Thread {

    private Student Student;

    Public GetThread (Student Student) {
        super ();
        This.student = student;
    }

    @Override public
    Void Run () {while
        (true) {
            synchronized (student) {
                System.out.println ( Student.getname () + "= =" + student.getage ());}}}

Setthread.java

public class Setthread extends thread{

    private Student Student;

    private int x = 0;

    Public Setthread (Student Student) {
        super ();
        This.student = student;
    }

    @Override public
    Void Run () {while
        (true) {
            //must be the same lock
            synchronized (student) {
                if (x%2 = 0) { C12/>student.setname ("admin");
                    Student.setage (in);
                else {
                    student.setname ("Manager");
                    Student.setage ();
                x + +;}}}}

Studentdemo.java

public class Studentdemo {public

    static void Main (string[] args) {

        //Create a shared resource for two threads
        Student Student = new Stude NT ();
        Create producer and Consumer
        setthread thread1 = new Setthread (student);
        GetThread thread2 = new GetThread (student);

        Open the producer and consumer thread
        Thread1.start ();
        Thread2.start ();
    }

The run effect (the ad that appears when stopped is not fully related to the thread's implementation, mainly because the buffer for the command window is not complete):

3 true realization of producers and consumers: producers after the production of consumers can be consumed, consumer consumption after the producers can produce such reciprocating:

Student.java

public class Student {

    private String name;
    private int age;

    The data private Boolean flag is not present by default
    ;

    Public String GetName () {return
        name;
    }
    public void SetName (String name) {
        this.name = name;
    }
    public int getage () {return age
        ;
    }
    public void Setage (int age) {
        this.age = age;
    }

    public Boolean Isflag () {return
        flag;
    }
    public void Setflag (Boolean flag) {
        This.flag = flag;
    }
    @Override public
    String toString () {return
        "Student [name=" + name + ", age=" + Age + "]";
    }

}

Setthread.java

public class Setthread extends thread{private Student Student;

    private int x = 0;
        Public Setthread (Student Student) {super ();
    This.student = student; @Override public void Run () {while (true) {//must be the same lock synchronized (Studen T) {//Judge if (Student.isflag ()) {try {Stud
                    Ent.wait (); catch (Interruptedexception e) {//TODO auto-generated catch block e.pr
                    Intstacktrace ();
                    } if (x%2 = 0) {student.setname ("admin");
                Student.setage (24);
                    else {student.setname ("manager");
                Student.setage (28);

                } x + +;
                Modify the tag Student.setflag (true); Student. Notify (); }

        } 
    }

}

Getthread.java

public class GetThread extends Thread {

    private Student Student;

    Public GetThread (Student Student) {
        super ();
        This.student = student;
    }

    @Override public
    Void Run () {while
        (true) {
            synchronized (student) {

                if (!student.isflag ()
                    ) { try {
                        student.wait ();
                    } catch (Interruptedexception e) {
                        //TODO auto-generated catch
                        block E.printstacktrace ();
                    }

                System.out.println (Student.getname () + "= =" + student.getage ());

                Student.setflag (false);
                Student.notify ();}}}

Operation Effect:
Studentdemo.java

/**
 * Waiting for wake-up:
 *      Three methods are provided in the object class:
 *      Wait (): waiting;
 *      Notify (): Wakes up a single thread;
 *      Notifyall (): Wakes up all threads;
 * @author YQ
 * * *
/public class Studentdemo {public

    static void Main (string[] args) {

        //Create two threads Common resources
        Student Student = new Student ();
        Create producer and Consumer
        setthread thread1 = new Setthread (student);
        GetThread thread2 = new GetThread (student);

        Open the producer and consumer thread
        Thread1.start ();
        Thread2.start ();
    }

Operation Effect:

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.