Search code examples
javajava-threads

is there any way to control the threads based on the objective they're "attached" to?


i need to set a thread priority, based on an object its "attached" to, i thought i might be able to get its ID somehow and then just give it a priority.

i tried to make my object static that way they'll be reachable, but i just cant control the thread based on its object.

in short, im trying to print something, and in the middle of the printing proccess the other threads are interrupting and printing stuff of thier own, without the current thread finished his print. thats why im trying to give it a priority. i've tried some pooling, but i discovered im not allowed to use that...


Solution

  • You don't need Thread priority (which may or may not actually do anything). You should use a lock

    public static final myLock = new Object();
    
    public void print1() {
      synchronized(myLock) {
        ...
      }
    }
    
    public void print2() {
      synchronized(myLock) {
        ...
      }
    }
    
    public void print3() {
      synchronized(myLock) {
        ...
      }
    }