开发者

Java concurrency, set flag in parent thread

开发者 https://www.devze.com 2023-02-09 15:49 出处:网络
This is a dilemma I’ve faced a few times and I can’t think of a clean solution. Say there is Class1 which keeps looping and spawns worker threads. I want the threads to be able to set a flag in Clas

This is a dilemma I’ve faced a few times and I can’t think of a clean solution. Say there is Class1 which keeps looping and spawns worker threads. I want the threads to be able to set a flag in Class1 to perf开发者_StackOverflow中文版orm a certain task. What I have been doing is have a static AtomicBoolean (flag) and a public static method in Class1 which sets the flag. However, this prevents me from having multiple instances of Class1.


Make the flag a class variable and then provide an interface for your worker thread to set and check the variable.

class Owner implements FlagAccess {
  private AtomicBoolean _flag;

  public boolean getFlag() {
    return _flag.get();
  }

  public void setFlag(boolean value) {
    return _flag.set(value);
  }
}

interface FlagAccess {
  public boolean getFlag();

  public void setFlag(boolean value);
}

class Worker extends Thread {
  private FlagAccess _access;
  public Worker(FlagAccess access) {
    _access = access;
  }

  public run() {
    _access.get();
    ...
    _access.set(true);
  }
}


The easy answer would seem to be to create a non-static AtomicBoolean in Class1, and pass either a reference to Class1 or to its AtomicBoolean to your worker tasks.

e.g. (note that this code is fairly horrible in most aspects - it doesn't e.g. use an ExecutorService for thread management)

class Class1 {

    AtomicBoolean flag;
    public void spawnTask (IndicatingTask task) {
       task.setFlagVariable(flag);
       new Thread(task).start();
    }
}

interface IndicatingTask extends Runnable {
    public void setFlagVariable(AtomicBoolean flag);
}


What about passing an instance of Class1 to your threads? So they can call class1.doStuff(). Don't forget to synchronize doStuff()


Rather than have a flag set in 'Class1' - would it work for worker threads to return a result/status ? If so look at using a Future for the worker(s). Use Executor framework for initiation and thread management.

Code examples etc. here - Java Concurrency In Practice

0

精彩评论

暂无评论...
验证码 换一张
取 消