Reputation: 345
I just want to run some threads as usual, I am not caring about how and when they switch between each other. But there is a last one thread remained that should not participate when other threads are running.
I have tried it by setting low priority to the last thread but it doesn't work and it switches between higher priority threads.
I got solution of it "a little bit", which is close to it by the below program but not exact what I want to do.
class ThreadDemo extends Thread {
static long value=0;
int no;
boolean flag;
public ThreadDemo(int no,boolean flag) {
this.no=no;
this.flag=flag;
}
public void run() {
int i=0;
boolean tempf=true;
while(tempf) {
if(flag == true || value >= 30) {
while(i<10) {
try{sleep(100);} catch(Exception e) {}
System.out.println("Thread # "+no+" is "+i);
i++;
value++;
}
tempf=false;
}
}
}
}
And then call it in main class like this
ThreadDemo th1 = new ThreadDemo(1,true);
ThreadDemo th2 = new ThreadDemo(2,true);
ThreadDemo th3 = new ThreadDemo(3,true);
ThreadDemo th4 = new ThreadDemo(4,false);
th1.start();
th2.start();
th3.start();
th4.start();
Here I want to execute run() method of th4 after completion of all three threads. But it actually invokes the run() method and also do switching between other threads.
Let me know if you want some clarification or info on it.
Upvotes: 0
Views: 59
Reputation:
try this.
ThreadDemo th1 = new ThreadDemo(1,true);
ThreadDemo th2 = new ThreadDemo(2,true);
ThreadDemo th3 = new ThreadDemo(3,true);
ThreadDemo th4 = new ThreadDemo(4,true);
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join();
th4.start();
Upvotes: 2