import java.util.concurrent.locks.ReentrantLock; public class Account implements Runnable { private static int num; private ReentrantLock reentrantLock = new ReentrantLock(); @Override public void run() { //上鎖 reentrantLock.lock(); reentrantLock.lock(); num++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("您是第" + num + "位訪客"); //解鎖 reentrantLock.unlock(); reentrantLock.unlock(); } }
public class Test { public static void main(String[] args) { Account account = new Account(); new Thread(account).start(); new Thread(account).start(); } }
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class TimeOut implements Runnable { private ReentrantLock reentrantLock = new ReentrantLock(); @Override public void run() { try { if (reentrantLock.tryLock(6, TimeUnit.SECONDS)) { System.out.println(Thread.currentThread().getName() + "get lock"); Thread.sleep(5000); } else { System.out.println(Thread.currentThread().getName() + "not lock"); } } catch (InterruptedException e) { e.printStackTrace(); } reentrantLock.unlock(); } }
public class Test01 { public static void main(String[] args) { TimeOut timeOut = new TimeOut(); new Thread(timeOut,"線程1").start(); new Thread(timeOut,"線程2").start(); } }