java thread lock base

The method of operation is defined 

package com.company; // package names
Import java.util.concurrent.locks.ReentrantLock;
Import java.util.concurrent.locks.Lock;
public class the implements the Runnable {Ticket
Private ticketnum int = 100; // global variables
Lock lock = new ReentrantLock (true) ; // objects
@Override
public void RUN () {// write RUN ()
the while (ticketnum> 0) {
Lock.lock (); // locking
the try {
IF (ticketnum> 0 ) {
the try {
the Thread.sleep (100); // working time
} catch (InterruptedException e) {
e.printStackTrace ();
}
.. String name = new new the Thread () currentThread () getName ();
System.out.println ( "threads" + name + "movie ticket sales" + ticketnum--);
}
}
a finally {
Lock .unlock (); // unlock
}
}
}
}


the method is added to the thread
package com.company;
import com.company.ticket;
public class shoupiao {
public static void main(String[] args) {
ticket ticket = new ticket();
Thread thread1 = new Thread(ticket,"窗口1");
Thread thread2 = new Thread(ticket,"窗口2");
Thread thread3 = new Thread(ticket,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}






Guess you like

Origin www.cnblogs.com/liuwenying/p/11311885.html