62,628
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Action {
private Semaphore roomManager = new Semaphore(2, true);
private Lock room1 = new ReentrantLock();
private Lock room2 = new ReentrantLock();
public void choose() {
try {
System.out.println(Thread.currentThread().getName() + "正在挑衣服.....");
Thread.currentThread().sleep(3000);
System.out.println(Thread.currentThread().getName() + "挑选完成准备试衣");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fitting() {
try {
roomManager.acquire();
if (room1.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "正在用1号试衣室");
Thread.currentThread().sleep(3000);
System.out.println(Thread.currentThread().getName() + "试衣完成,1号试衣室可以使用了");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
room1.unlock();
}
} else if (room2.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + "正在用2号试衣室");
Thread.currentThread().sleep(3000);
System.out.println(Thread.currentThread().getName() + "试衣完成,2号试衣室可以使用了");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
room2.unlock();
}
}
roomManager.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pay(boolean flag) {
if (flag) {
try {
System.out.println(Thread.currentThread().getName() + "正在买单.....");
Thread.currentThread().sleep(3000);
System.out.println(Thread.currentThread().getName() + "买单购物结束");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + "决定不买了");
}
}
}
public class Person extends Thread {
private Action action;
private int count;
private boolean flag;
/**
* @param action
*/
public Person(String name, Action action, int count, boolean flag) {
super(name);
this.action = action;
this.count = count;
this.flag = flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (count > 0) {
action.choose();
action.fitting();
count--;
}
action.pay(flag);
}
}
public class test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Action act = new Action();
Person p1 = new Person("P1", act, 1, true);
Person p2 = new Person("P2", act, 2, true);
Person p3 = new Person("P3", act, 1, false);
p1.start();
p2.start();
p3.start();
}
}