简体   繁体   中英

Sharing common array between multiple threads

I am trying to implement a 2phase Resource Lock Deadlock Prevention algorithm in Java. After multiple attempts, I have settled on creating a SimpleProcess class that implements the Runnable interface that will act as my thread. The structure of SimpleProcess looks somewhat like this:

public class SimpleProcess implements Runnable
{
    private int pid; // process id
    private ArrayList<Integer> requiredRes; // originally required resources
    private int[] remainingRes; // resources that are still required
    private boolean status; // whether process is completed running or not

    public SimpleProcess() {
        pid = 0;
        status = false;
    }

    public SimpleProcess(int id, ArrayList<Integer> res) {
        pid = id;
        requiredRes = res;
        remainingres = requiredRes;
        status = false;
    }

    public int getPid() {
        return pid;
    }

    public int[] getRequiredRes() {
        return requiredRes;
    }

    public int[] getRemainingRequiredRes() {
        return remainingRes;
    }

    public boolean getStatus() {
        return status;
    }

    public void run() {
        System.out.println("Process " + pid + " started.");
        // do something
        System.out.println("Process " + pid + " is complete.");
    }

}

My main class will contain a variable that contains lock status for each resource. This variable is implemented as final Lock[] locked_res = ReentrantLock[nr] . What I need help is with finding a way to share this same variable whose value can be changed by each thread to be shared among all the threads (SimpleProcess instances).

You can use the volatile keyword for multi-thread sharing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM