A sample program on threads to demonstrate how to start a thread and run it for a specified period of time (say 2 minutes in this below example).
Code begins here.........
Code begins here.........
import java.util.Calendar; class ThreatRunner extends Thread{ @Override public void run() { System.out.println(" in the thread"); try { sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadWithTimer { public static void main(String[] args) { ThreatRunner tr=new ThreatRunner(); Thread tt=new Thread(tr); Calendar mycal=Calendar.getInstance(); long currentTimer=System.currentTimeMillis(); System.out.println(mycal.getTime()); while ((System.currentTimeMillis()-currentTimer)< 2*60*1000){ tt.run(); } System.out.println(mycal.getTime()); } }
Output: Thu Mar 06 12:17:04 IST 2014
in the thread
in the thread
Thu Mar 06 12:19:04 IST 2014
in the thread
in the thread
Thu Mar 06 12:19:04 IST 2014
No comments:
Post a Comment