I am writing a program in j2me and i want to have a thread that starts when the program launches but wll sit doing nothing until the user presses ok. The thread will then go and carry out a task and then go idle again until the user presses ok again.

But what has got me confused is, i am reading a tutorial about threads and it says once the thread has carried out its run method the thread terminates. Does this mean the thread is killed altogether? How would i keep it alive after carry out its first task?

Recommended Answers

All 4 Replies

Why start a thread that does nothing?
Start one every time you need one to carry out the task. Let it do the task and exit/end.

Why start a thread that does nothing?
Start one every time you need one to carry out the task. Let it do the task and exit/end.

I honestly dont know. My tutor told me to do it like this.

Threads can be written in a number of ways, but if they complete their run() method, they will terminate (die). You can easily get around this by putting the code to execute in a while loop that simply executes a

break;

if you want it to exit.

What it sounds like you really want to do is spawn a thread when the user presses the button, not when the program starts. How this would work conceptually is the button's ActionListener would create a new instance of YourThreadClass and execute its run() or start() method. This thread would run on its own, complete the task, and die. Pressing the button again would spawn a new thread which could then handle a different task (potentially while the the other thread is still running).

But what has got me confused is, i am reading a tutorial about threads and it says once the thread has carried out its run method the thread terminates. Does this mean the thread is killed altogether? How would i keep it alive after carry out its first task?

I assume this is supposed to be an assignment on threads, otherwise it's quite useless, but nonetheless, just because your thread has 'performed' the code that should be run when you click your button, doesn't mean it's task ended.

the actual task of your thread is to run in the background until you quit your program, detecting whether or not a button has been pressed, and, once a button was pressed, make a call to the appropriate method. this doesn't mean it's duty stops, just re-set the flg and go back to detecting whether or not a button has been pressed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.