How do I create methods for a thread? - java

I'm writing an android application.
In the main thread, it is possible to define methods and then call the methods, which helps keep the code clean. In a new thread, how does one define methods, to avoid writing all the code in "one block"? Is it possible to call methods defined in the main thread, or can you define them inside the new thread somehow?
So to be clear, what I want to do is this:
volatile Runnable feedToBuffer = new Runnable()
{
#Override
public synchronized void run()
{
if(boolean)
{
MethodA();
}
else
{
MethodB();
}
}
and not this:
volatile Runnable feedToBuffer = new Runnable()
{
#Override
public synchronized void run()
{
if(boolean)
{
//Code that was in MethodA
}
else
{
//Code that was in MethodB
}
}
}
Is that possible?
I realize this info is probably out there somewhere, but haven't found it, so really grateful for any help. :)

It's perfectly possible. Thread is just a sequence of actions, and if it involves a method call, it will be executed within that sequence. It doesn't matter.
Threads are in no way tied to the structure of your code. The main difference between the threads you start and the one you have already when the app starts is the points of entry. When Android starts the main thread, it enters your app in many points, in the activity that would be the lifecycle calls like onCreate() or button click listeners. When you create a new thread, your point of entry is the run method from where you can call anything you want.
There is also a difference in that the main thread runs an event loop. Basically, there is a queue of messages that it has to process. Each time something arrives to the queue, it processes the message, then goes back to waiting. In that sense the main thread never ends. Your thread, however, stops when it reaches the end of the run method. Of course, you can implement a similar event loop for your thread yourself.
Other than that there are no fundamental differences in how the threads operate, you can call methods from any thread freely. Of course, there are rules of multithreading like avoiding blocking the main thread, synchronization, and so on, but it's too much to cover in one answer.

Related

Restarting a thread after it has been left

I have thread which contains a loop
while(isRunning){
}
isRunning is a Boolean variable with the value true, when some clicks on a button it gets false and so it leaves the loop and the run() function of the thread.
I want to create another button that on click it will reenter the run() function.
I am not sure if when I leave the run() function the thread dies or just stops.
I have tried using thread.run() but it didnt work.
Also I have looked for an answer in other's people questins about this matter but nothing seemed to help me. Thanks for the help
When a thread is finish processing it's code, There's no way of restarting it. You can either:
Create a new thread and pass the Runnable to that thread.
If you need to use that run() method often, use an Executor. You can use Executors.newSingleThreadExecutor(), which will supply you with a worker thread. (Reusable thread).
class Example {
static ExecutorService executor = Executors.newSingleThreadExecutor();
static Runnable run = new Runnable() {
public void run() {
}
};
public static void main(String[] args) {
//anytime you wanna run that code..
executor.execute(run);
}
}
If your thread runs to its end, it stops.
It will remain there for you to collect its return status until the thread is cleaned up.
To restart within the same thread, you need an extra control flow.
For instance:
while (restarted) {
while (isRunning) {
}
// Wait for a restart or end click
}
That is what so called worker threads in a thread pool do, which are intended for maximum performance.
But logically, you will probably simply want to create a new thread object and start that one.
new Thread(p).start();
Please read through java concurrency tutorial.
http://docs.oracle.com/javase/tutorial/essential/concurrency/
Just Maybe, guarded blocks might be useful for your case but your case is a little vague to recommend anything specific.
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Method Not Executing in a Synchronous Manner

I have a MVC-based Java application which I am building, and there is a particular method within my controller (shown below) which behaves as follows:
The model is updated via the initialize method, as I would intend.
The update to the view is not occurring because the model.start() method never terminates (since it is an infinite while loop).
I want to have my view to update first, and then be able to start() my model. How do I alter my code to get the desired behavior?
I suppose one workaround would be replace the model.start() line with code that fires an event which my model is able to observe, but I have not tried that yet, because I want to understand the source of my problem.
Also, I have no idea if this is relevant, but my main application class defines a separate thread for my swing components via SwingUtilities.invokeLater(new Runnable()..., and my view is made up of swing components. There may be some issue related to multiple threads executing, and if so, that would explain why my initializedPerformed() method is not executing in a synchronous way.
Method in the controller which does not behave like I expect/want:
public void initializePerformed(Event e) {
model.initialize(e);
view.getPanel().setName(model.getName());
model.start();
}
model.start():
public void start() {
while (true) {
}
}
If you need model.start() at all, which I highly doubt you do, then start it in a separate thread like this:
new Thread() {
public void run() {
model.start();
}
}
If model is actually inheriting from Thread, then you shouldn't be overriding start() at all. You should override run(), which is called after Thread.start(), and after the new thread has actually been created. If you override start(), no new threads will be created.
From what I remember about swing, all operations must be done by the "main" app thread (I forgot the technical name of it).
The pattern is : create threads to process your data, and leave the main thread only for display. When there is an event that should be displayed, notify the view but let the main thread change it (typically use the semaphore pattern, but if you find it too complex, you can also have an infinite loop that looks what's new each 100 ms for example and calls wait() to check again: business threads will change variables accessible to the main thread.
Best Regards,
Zied Hamdi
http://1vu.fr

Thread as constructor or run()

Is there any difference between creating a thread using the run() method as opposed to using the a constructor?
I noticed that I can start the thread and it acts the same in both ways.
new Thread MyThread().start
For example, as a constructor:
public class MyThread extends Thread{
public MyThread(){
// Do something
}
}
or as the run() method
public class MyThread extends Thread{
public void run(){
// Do something
}
}
Is there any difference between constructor or run()? Thanks!
It does not act the same in both cases
These cases are entirely different.
First, you probably need to learn about Threads and non-blocking processes. A Thread is used to do something asynchronously. So if you wanted to do some background task whilst doing something else then you would use a Thread. A good example is a GUI; you need one Thread to listen for GUI events (mouse clicks, button presses) and another to do any long running processing.
Now, onto your examples.
In Java a Thread consists of a run method that executes asynchronously when the start method is called. So when overriding Thread you change the run method. In reality you should never override Thread, you should use the constructor that takes a Runnable. There are many reasons for this, you should read up on concurrency.
Any code you place in your Thread constructor will be executed in the Thread that calls your constructor so this is not called asynchronously.
If you put the code in the run method, a new thread will be started upon invocation of start, which uses the run method as its starting point. If you put the code in the constructor, however, it will be run in the same thread as that which invoked the constructor, because a constructor is a special case of a method. Thus, if you want to start something in a new thread, put it in run, otherwise, put it in the constructor. Also, if you want to start a thread, never call Thread.run, because of the same reason not to put code in the constructor. Always call Thread.start().
The key difference is this:
The code in your constructor is executed immediately and synchronously when the constructor is invoked.
The program will stop and wait for that code to complete before moving on to the next line of code.
If you put the code inside run() method AND use Thread.start(), the code will be executed in a separate thread (i.e. it will run asynchronously).
Your program will continue to execute (moving to the next line of code immediately) while the code in your run() method runs in parallel.
This is helpful if the code in run() takes a very long time to execute.
That's because your program can continue to do other things while it waits for the thread to finish its work.
There is a difference. The constructor that creates the Runnable or subclass thereof runs in the main thread.
When starting a thread using:
new Thread(myRunnable).start();
you'll actually have run( of myRunnable run in the new thread.
NB You'll want to have a reference to the thread object in many cases. This code example is merely illustrative
On another note, never, ever, ever, give a thread this if starting within a constructor. Your computer could explode, or asphyxiation, drowning, or poisoning may occur.

Call a listener method from a worker thread but have it run on the thread that added the listener

I'm writing a TCP server class that I want to be self-contained. That is, the applications that use this class need not worry about the internal worker threads. The TCP server class has a start() method and I want to be able to call the listener's methods on the same thread that called start() (under normal use, the main thread). This is probably better explained with code:
public class ProblemExample {
private Listener mListener;
public ProblemExample() {
mListener = new Listener() {
#Override
public void fireListener() {
System.out.println(Thread.currentThread().getName());
}
};
}
public void start() {
mListener.fireListener(); // "main" is printed
new Thread(new Worker()).start();
}
public interface Listener {
public void fireListener();
}
private class Worker implements Runnable {
#Override
public void run() {
/* Assuming the listener is being used for status updates while
* the thread is running, I'd like to fire the listener on the
* same thread that called start(). Essentially, the thread that
* starts the operation doesn't need to know or care about the
* internal thread. */
mListener.fireListener(); // "Thread-0" is printed
}
}
}
I've tried searching for this but I'm not really sure what to search for. The best I've found is that SwingWorker seems to do this, but I can't find out how.
Can anyone shed some light?
What you are asking for is theoretically impossible without explicit cooperation from the client thread (the one that called start()). Just stop to think about it: the main thread is always busy running some specific code, in some specific method. The complete call stack is dedicated to the current call. Now you would like to interrupt that and start executing listener code out of the blue.
The way Swing achieves this is by running a main event loop in the Event Dispatch Thread. In this loop, you can imagine instances of Runnable being pulled off of a queue and their run methods called in turn. Only when one run method returns can the next one be called.
This is what you need to design for your case as well, but I'm not sure whether you had something like that in mind. The only alternative is explicit support for listener methods being executed on a foreign thread.

Interrupt a thread in java

I found this solution to know if a thread has been interrupted.
public class OurThread extends Thread(){
private volatile boolean stop = false;
public void run(){
while (!stop) {
//Do your actions
}
}
}
But my run method is only executed once, so It doesnt make sense to put it insisde a while loop. Another approach I found, is to check the Thread.isInterrupted() flag, and then terminate the thread. My run() method is pretty long so I would have to check lots of times this condition making my code dirty.
I have to apply this into four diferents processes so im trying to find a simpler, cleaner soution. I was hoping if is there something like:
try{//my code}
catch(interrumption)
The problem is that since my thread is interrumped by using future.cancel(), the interruption is not thrown inside my run() code, then i cant do that either.
Any suggestion?
By now im checking lots of times between the code if the thread has been cancelled.
Thanks :)
Firstly, don't extend Thread, you should implement Runnable or Callable.
Secondly you can add a method like
static void checkInterrupt() {
if(Thread.currentThread().isInterrupted())
throw new IllegalStateException("Interrupted");
}
and place this in the four places. This doesn't add much code and isn't as ugly as a task which won't stop.
Your task ( Runnable or Callable) can't be interrupted unless it has inbuilt mechanism to respond to interrupts. Also it depends on your design; like, when exactly task expects to be interrupted. Usually we do when the task has reached a safe state.
So you check if interrupt is received and then respond appropriately. To reuse code you can use approach suggested by #Peter.

Categories