我是多线程的新手,非常感谢您的帮助。
编辑后的代码和问题
我想使用ReentrantLock类来控制对两个ArrayList的访问。第一个是orderList,第二个是prepareOrders ArrayList。 Class Chef(扩展了Thread)的两个对象每次都希望从数组列表中删除订单,休眠一段随机的时间,然后将订单放置在prepareOrders数组列表中,直到OrdersList为空。这是我当前的代码:
厨师班
import java.util.concurrent.locks.ReentrantLock;
public class Chef extends Thread{
private String name;
private ReentrantLock orderLock;
private ReentrantLock preparedLock;
private String orderName;
private Object useForLocking = new Object();
public Chef(String name,ReentrantLock orderLock,ReentrantLock preparedLock){
this.name = name;
this.orderLock = orderLock;
this.preparedLock = preparedLock;
}
public void run(){
while(Restaurant.orderList.size()>0){
try{
getOrder();
System.out.println(name +" is preparing "+orderName+"\n");
Thread.sleep(Math.round(Math.random()*100));
outputOrder();
}catch(Exception e){
System.out.println("run exception: "+e+"\n");
}
}
}
public void getOrder(){
if(orderLock.tryLock()){
orderLock.lock();
try{
orderName = Restaurant.orderList.remove(0);
}catch(Exception e){
System.out.println("getOrder exception: "+e+"\n");
}finally{
orderLock.unlock();
synchronized (useForLocking){
useForLocking.notify();
}
}
}else{
try{
synchronized (useForLocking){
useForLocking.wait();
}
}catch(Exception e){
System.out.println("getOrder wait exception: "+e+"\n");
}
}
}
public void outputOrder(){
if(preparedLock.tryLock()){
preparedLock.lock();
try{
Restaurant.preparedOrders.add(orderName);
}catch(Exception e){
System.out.println("outputOrder exception: "+e+"\n");
}finally{
preparedLock.unlock();
synchronized (useForLocking){
useForLocking.notify();
}
}
}else{
try{
synchronized (useForLocking){
useForLocking.wait();
}
}catch(Exception e){
System.out.println("outputOrder wait exception: "+e+"\n");
}
}
}
}
餐厅课(主)
import java.util.concurrent.locks.ReentrantLock;
import java.util.ArrayList;
public class Restaurant{
public static ArrayList<String> orderList = new ArrayList<String>();
public static ArrayList<String> preparedOrders = new ArrayList<String>();
public static void main(String[] args) {
orderList.add("Cheese Pizza");
orderList.add("Hotdog");
orderList.add("Hamburger");
orderList.add("Cheese burger");
orderList.add("Chicken Nuggets");
orderList.add("Chicken Burger");
ReentrantLock orderLock = new ReentrantLock();
ReentrantLock preparedLock = new ReentrantLock();
Chef c1 = new Chef("Chef John",orderLock,preparedLock);
Chef c2 = new Chef("Chef Mark",preparedLock);
c1.start();
c2.start();
}
}
输出
Chef John is preparing Cheese Pizza
Chef John is preparing Hotdog
Chef John is preparing Hamburger
Chef John is preparing Cheese burger
Chef John is preparing Chicken Nuggets
Chef John is preparing Chicken Burger
为什么第一个线程未解锁?