【问题标题】:How do I queue threads to pause and run only when another thread is run?如何仅在运行另一个线程时将线程排队以暂停和运行?
【发布时间】:2018-04-17 05:03:27
【问题描述】:

我创建了一个网络停车场系统,其中包含两个入口客户端、两个出口客户端和一个服务器。我的目标是在停车场没有空位时让汽车在入口处排队。

这是我到目前为止所做的:

import javax.swing.JFrame;
import javax.swing.JOptionPane;

@SuppressWarnings("unused")
public class SharedState extends Thread{

private SharedState mySharedObj;
private String myThreadName;
private int totalSpaces;
private int groundSpaces;
private int firstSpaces;
private boolean accessing=false; // true a thread has a lock, false otherwise
private int threadsWaiting = 0; // number of waiting writers
JFrame Notification = new JFrame();

// Constructor  
SharedState(int groundFloor, int firstFloor) {
    groundSpaces = groundFloor;
    firstSpaces = firstFloor;
}

//Attempt to aquire a lock
public synchronized void acquireLock() throws InterruptedException{
    Thread me = Thread.currentThread(); // get a ref to the current thread
    ++threadsWaiting;
    while (accessing) {  // while someone else is accessing or threadsWaiting > 0
        //wait for the lock to be released - see releaseLock() below
        wait();
    }
    // nobody has got a lock so get one
    --threadsWaiting;
    accessing = true;
}

// Releases a lock to when a thread is finished
public synchronized void releaseLock() {
    //release the lock and tell everyone
    accessing = false;
    notifyAll();
    Thread me = Thread.currentThread(); // get a ref to the current thread
}

public synchronized String processInput(String myThreadName, String theInput) throws InterruptedException 
{
    String theOutput = null;

    // Check what the client said       
    if (theInput != null) 
    {           
        //Correct request
        if(myThreadName.equals("GroundFloorEntrance"))
        {
            if(groundSpaces > 0)
            {
                groundSpaces--;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle arrived.\nGround floor spaces = " + groundSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else if (firstSpaces > 0)
            {
                firstSpaces--;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle arrived.\nFirst floor spaces =  " + firstSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else
            {
                theOutput = "No spaces available, please queue.";
            }
        }
        if(myThreadName.equals("FirstFloorEntrance"))
        {
            if(firstSpaces > 0)
            {
                firstSpaces--;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle arrived.\nFirst floor spaces = " + firstSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else if (groundSpaces > 0)
            {
                groundSpaces--;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle arrived.\nGround floor spaces = " + groundSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else
            {
                theOutput = "No spaces available, please queue.";
            }
        }

        if(myThreadName.equals("GroundFloorExit1"))
        {
            if(groundSpaces < 20)
            {
                groundSpaces++;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle departed.\nGround floor spaces = " + groundSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else
            {
                theOutput = "Vehicle departed.\nGround floor spaces = " + groundSpaces + "\nTotal spaces = " + totalSpaces;
            }
        }
        if(myThreadName.equals("GroundFloorExit2"))
        {
            if(firstSpaces < 20)
            {
                firstSpaces++;
                totalSpaces = groundSpaces + firstSpaces;
                theOutput = "Vehicle departed.\nFirst floor spaces = " + firstSpaces + "\nTotal spaces = " + totalSpaces;
            }
            else
            {
                theOutput = "Vehicle departed.\nFirst floor spaces = " + firstSpaces + "\nTotal spaces = " + totalSpaces;
            }
        }
    }

    //Return the output message to the Server
    JOptionPane.showMessageDialog(Notification, theOutput);
    System.out.println("\n" + theOutput);
    return theOutput;
}   
}

我希望汽车在没有可用空间时排队,并在汽车退出时自动运行。我相信当退出客户端之一运行时,我需要有效地将线程排队以在 IF 语句中运行。但是,我不确定该怎么做。

【问题讨论】:

标签: java multithreading


【解决方案1】:

使用这种机制。在你的项目中以合适的方式使用这种机制。最初将所有可用的停车位添加到队列中

 public static BlockingQueue blockingQueue = new ArrayBlockingQueue<Integer>(10);

public static void main(String[] args) {
    Thread t1 = new Thread(()-> {
        while(true){
            Random random = new Random();
            try {
                int i = random.nextInt(10);
                if(i!=8) { // a car request parking space
                    System.out.println("waiting until parking available");
                    int j = (int) blockingQueue.take();
                    System.out.println("released parking space "+j+" to requested car " );
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });
    Thread t2 = new Thread(()->{
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while(true){
            Random random = new Random();
            try {
                int i = random.nextInt(10);
                if(i!=5) { //car went out from parking space .add avilable slot to queue
                    System.out.println("add  free parking space:" + i +" to queue");
                    blockingQueue.put(i);
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    t1.start();
    t2.start();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多