Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Scheduling with Thread  RSS feed

 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any body expalin how to write a method (Using Thread)which will be executing every 1 minute and get the database Search.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
put a while loop inside the thread run method.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have done like below But it is not executing run once we invoke it is stopped after printing Two ;I don't know the basics of thread,
package asia.test;
public class FaultModelRefresher extends Thread{

public FaultModelRefresher(){
System.out.println("One");
Thread t=new Thread();
t.start();
System.out.println("Two");
}
public void run(){
int i=0;
System.out.println("Three");
try{
while(true){
wait(10000);
System.out.println("Yes = "+i);
i++;
}
}catch(Exception e){
System.out.println("Exception in FaultModelRefresher = "+e);
}

}
}
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while calling from another class like this
FaultModelRefresher fm=new FaultModelRefresher();
fm.start();
getting an exception
java.lang.IllegalMonitorStateException: current thread not owner
Can anybody tell i want just keep on executing the run method with a wait option.
 
imre leber
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good thing i am just getting ready for the SCJP.
You get an IllegalMonitorStateException because you are calling wait outside a synchronized block.
If you use wait() you have to first have a lock on it so for example:

should work
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the original problem, you can also use

instead of

And then you won't need any synchronization.
Or, use classes from java.util:
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks You all.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!