java - Threads running at same time instance -
i have requirement threading need initiate thread run continuously doing db operations . second thread present needs run every 30 secs. job of second thread killing first thread , start new instance of first thread.
i tried several ways achieve not able same.
public class threadmain { public static void main(string[] args) throws interruptedexception, brokenbarrierexception{ final cyclicbarrier gate = new cyclicbarrier(3); thread t1 = new thread(){ public void run(){ try { gate.await(); while(true) { system.out.println("thread1"); break; } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (brokenbarrierexception e) { // todo auto-generated catch block e.printstacktrace(); } }}; thread t2 = new thread(){ public void run(){ try { gate.await(); while(true) { system.out.println("continiously running thread:-thread2"); } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (brokenbarrierexception e) { // todo auto-generated catch block e.printstacktrace(); } }}; t1.start(); t2.start();
this seems work nicely:
// thread runs forever. volatile static thread foreverthread = null; static class forever implements runnable { @override public void run() { try { while (true) { thread.sleep(1000); system.out.println("for ever!"); } } catch (interruptedexception ex) { // quit if interrupted. } } } // stop thread if running. private static void stopforeverthread() throws interruptedexception { // skip if non-existent. if (foreverthread != null) { // make sure no-one else doing it. synchronized (foreverthread) { // still not null? if (foreverthread != null) { // interrupt it. foreverthread.interrupt(); // wait finish. foreverthread.join(); // clear it. foreverthread = null; } } } } private static void restartforeverthread() throws interruptedexception { system.out.println("restarting..."); // stop if running. stopforeverthread(); // start again. foreverthread = new thread(new forever()); foreverthread.start(); system.out.println("restarted"); } public static void start() throws interruptedexception { // start up. restartforeverthread(); // timed event restart it. timer restarttimer = new timer(true); restarttimer.scheduleatfixedrate( new timertask() { @override public void run() { try { // restart every few seconds. restartforeverthread(); } catch (interruptedexception ex) { // interrupted during restart - log it. } } // every few seconds. }, 0, 10 * 1000); } public static void main(string args[]) { try { // start up. start(); // hang around while - see happens. thread.sleep(60 * 1000); } catch (throwable t) { t.printstacktrace(system.err); } }
Comments
Post a Comment