Java Thread example needed

iosoft

PC enthusiast since MS DOS 5
Skilled
I am having little problem with a Java Thread Coding.

1. Single Background Thread will run from Main.
2. The Thread will run() every 15mins and then go to sleep.
3. If needed, the Main will forcefully call the run() method of that Thread.
 
Below is an example.

Code:
class XThread extends Thread {

	XThread() {
	}
	XThread(String threadName) {
		super(threadName); // Initialize thread.
		//System.out.println(this);
		start();
	}
	public void run() {
		//Display info about this particular thread
		System.out.println("Thread started.");
	}
}

public class ThreadExample {

	public static void main(String[] args) {
		Thread thread1 = new Thread(new XThread(), "thread1");

		//Start the thread
		thread1.start();
		while (true){
			try {
				//The sleep() method is invoked on the main thread to cause a one second delay.
				Thread.currentThread().sleep(1000);
			} catch (InterruptedException e) {
			}
			//Display info about the main thread
			System.out.println(Thread.currentThread());
			System.out.println("Implement your function here.");
		}
	}
}
 
^^ That example doesn't really answer to the question ..

i think the following code is better

Code:
class CustomThread extends Thread {

   CustomThread() {}

   

   CustomThread(final String threadname) {

	setName(threadname);

   }

   

   @Override

   public void run() {

	while (true) {

	   System.out.println(Thread.currentThread().getName() + " executed,waiting for 1s");

	   try {

		Thread.sleep(1000); // 1000 = 1s , so for 15 minutes insert the value 1000*60*15

	   }

	   catch (final InterruptedException ie) {}

	}

   }

}

public class MainThread {

   public static void main(final String... args) {

	System.out.println("main thread triggered");

	System.out.println("custom threads triggered");

	new CustomThread("thread 1").start();

	//new CustomThread("thread 2").run();

	System.out.println("main thread ended");

   }

}

in the above example, Thread 1,2 will run independently of main, infact when u run the program, main should finish before either of the threads.

U can directly invoke run() as a normal method of an instance, but using "extends Thread" will result in an anomaly, where the content of run() method also be executed separately for main() so, so the code will go into an infinite loop with all threads including main() running, if u uncomment the 2nd last line of main().

The better approach is to implement Runnable.
 
Back
Top