FAQ Database Discussion Community


Error in run() method when using Thread.sleep()

java,multithreading,runtime-error,runnable,interrupted-exception
I am trying to run an Elevator instance in its own thread. The run() method is being called, but there must be some error in my code that is preventing it from running. My code compiles and runs without errors, but the "Elevator starting up" is never printed. I think...

Lambda that does absolutely nothing

java,lambda,java-8,runnable
I needed to have a lambda expression of the functional interface Runnable that did nothing. I used to have a method private void doNothing(){ //Do nothing } and then use this::doNothing. But I've found an even shorter way to do this....

Android: Display current track Info in mediaplayer using webpage

android,android-asynctask,inputstream,android-mediaplayer,runnable
I am a learner and developing an Android App to play live stream. It is working properly except 1 issue. I want to show title of currently playing Track which is available on a webpge. For this purpose I have used a textView and tried to use Asynchronous Task and...

synchronized(…) on a code block with var=Thread.currentThread() [duplicate]

java,multithreading,runnable
This question already has an answer here: What does 'synchronized' mean? 13 answers I'm reading a code with this class: public class MultiThreadedServer implements Runnable { // some more code protected Thread runningThread = null; public void run() { synchronized(this) { this.runningThread = Thread.currentThread(); } // lots of code...

Anonymous runnable and memory leak

java,runnable,anonymous-class
Let's say we have a some static method in some static class which runs some operations(has a runnable) in separate thread and returns result by some listener: public class SomeStaticClass { private static ExecutorService mExecService = Executors.newCachedThreadPool(); ........ public interface IDataLoadCompleteListener { public void onDataLoadComplete(Object result); } ........ public static...

Interactions between Java threads [duplicate]

java,multithreading,runnable
This question already has an answer here: Stopping Thread in Java 1 answer I have two classes (A & B) which implements Runnable. Both threads are executed in this way: A a = new A(); new Thread(a).start(); B b = new B(); new Thread(b).start(); I need to stop/wait/resume thread...

Possible execution result

java,multithreading,runnable,java-threads
public class Messager implements Runnable { public static void main(String[] args) { new Thread(new Messager("Wallace")).start(); new Thread(new Messager("Gromit")).start(); } private String name; public Messager(String name) { this.name = name; } public void run() { message(1); message(2); } private synchronized void message(int n) { System.out.print(name + "-" + n +...

How to interrupt a thread by button listener

java,android,runnable,thread-sleep,interrupted-exception
I have a button listener witch include a thread sleep and another button listener. Second button listener must interrupt this thread and I don t know how to do this: My code: button1.setOnClickListener (new View.OnClickListener() { @Override public void onClick(View v) { .......... button1.setEnabled(false); button1.setVisibility(View.GONE); button2.setVisibility(View.VISIBLE); button2.setEnabled(true); new Thread(new Runnable()...

Android: button to start and stop a loop [duplicate]

android,runnable,timertask
This question already has an answer here: Reschedule timer in android 2 answers I would like to repeat updating some imageview in a layout when a button is pressed and then stop updating when the same button is pressed again. The code is done as follows: Code: btn_start.setOnClickListener(new View.OnClickListener()...

How to use a method in Multi-Threads Class which implements Runnable

java,multithreading,arraylist,runnable
I am making a multi-threaded application. The class which implements Runnable has a method which returns ArrayList. How do i use that method in my main? class SearchThread implements Runnable { private ArrayList<String> found; //Constructor public SearchThread (String[] dataArray) {/**/} public void run() { try{ //Do something with found }...

Handler & Runnable for Android Timer

java,android,handler,runnable,android-handler
I'm trying to display a String array in a TextView, one item at a time, every time an interval in milliseconds ends. I've been recommended this code: package com.tt.blanker; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Button; import android.widget.TextView; import java.util.StringTokenizer; /** * Created by Gonzalo on 08/04/2015....

How to remove/postDelayed runnables in Java?

java,runnable
Upon an event, I'd like to run a task/runnable but delay it's execution in 2 seconds. During these 2 seconds, if the same event occurs, I'd like to remove the previous task and re-post it to run - again delayed by 2 seconds. An example scenario would be background compilation....

Android Runnable Handler not stop at specified intervals(seconds)

java,android,runnable,android-handler
I am using Runnable Handler to update my UI at specified intervals . However on button click event my this timer stops but at specified intervals it continues to go own . Here is my code . public class MainActivity extends ActionBarActivity { public TextView myCounter; private int mInterval=50; private...

Some concurrency-design in java

java,multithreading,concurrency,runnable,java-threads
I need to retrieve a huge picture from a server but the server can't do that because the image is too big. I can give "coordinates" so that I can retrieve small parts of that picture. So I split the picture in to 100 tiles and than append 10 tiles...

Schedule to run a method at periodic time in java

java,methods,timer,scheduler,runnable
I have to schedule a method to be executed when starting and periodically thereafter at intervals of 1 minute. For that I have done this: public void init(){ loadConfig(); //method which needs to be executed periodically Timer scheduler = new Timer(); scheduler.scheduleAtFixedRate(loadConfig(),60000,60000); } This is giving an error and it...

How do I manage hibernate transactions in a timertask?

java,hibernate,exception,runnable,jta
I am currently trying to make a hibernate query inside of a TimerTask (Runnable). This task makes no saves or updates to the database. It just retrieves a list of jobs. Anytime I run this task, I get HibernateException: Unable to locate current JTA transaction. I believe this has to...

Handler postdelayed is not fired after given delay interval when quitting the app in android?

android,handler,runnable,postdelayed
Code Snippet: Handler handler= new Handler(); handler.postDelayed(networkRunnable, 10000); /** * A runnable will be called after the 10 second interval */ Runnable networkRunnable= new Runnable() { @Override public void run() { //Not fired if I quit the app before 10 seconds after 1 second. } }; Setting Handler post delayed...

ScheduledExecutorService not triggering correctly

java,multithreading,runnable,scheduledexecutorservice
I am attempting to have a method triggered after a delay with the following code: ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new UpdateTDDBRejections(), 5, 10, TimeUnit.SECONDS); It should wait for the delay to pass, trigger the "UpdateTDDBRejections" method, which is in another, Runnable, class, which will print out a phrase and then...

No response from second client socket

java,multithreading,sockets,response,runnable
I am working with Java sockets. I have a server socket and two client sockets. My problem is, that the first client socket submits its message to my server socket, and the message from the second client socket is not arriving at the server socket. That means, that for the...

How do I change the rate or period of a repeating task using ScheduledExecutorService?

java,android,runnable,recurring,scheduledexecutorservice
I have a modified version of the bluetooth chat sample app. I have set up a ScheduledExecutorService which sends a command over bluetooth at a predefined rate using scheduleAtFixedRate. I have set up a PreferenceActivity to allow the period to be modified by the user. But I'm unsure how to...

JavaFX show loading dialog for longer operations

asynchronous,concurrency,javafx,runnable
I got some operations in my Controller class which could take some time. So I want to show a loading dialog while this operation is running. I tried this: Platform.runLater(new Runnable() { @Override public void run() { loadingDialog.show(); } }); Boolean opSuccess = myService.operate(); Platform.runLater(new Runnable() { @Override public void...

Spring MVC controller executes task asynchronously in Servlet 2.5

java,spring-mvc,asynchronous,concurrency,runnable
I am working on a Spring MVC application on Java 6 JVM running in a Servlet 2.5 (Tomcat) environment. I need to develop a controller method that will perform a long running task (large database query, generate report and deliver email to user). Justifiably, I want the task to run...

Runnable concurrency

java,concurrency,runnable,jmonkeyengine
I am playing around with JMonkeyEngine. While doing this i play JavaFX MediaPlayer. This MediaPlayer takes a Runnable to handle what's to do, when the media finished: mp.setOnEndOfMedia(new Runnable() { @Override public void run() { }} I want to do sth. like this: mp.setOnEndOfMedia(new Runnable() { @Override public void run()...

How to stop handler.postDelayed in for-loop?

java,android,for-loop,handler,runnable
I saw no real answer for this type of using "handler.posDelayed". So, I execute "handler.posDelayed" multiple times with a for-loop. The problem is, when I leave the activity and restart it, the new objects AND the old ones from the handler are executed too. I don't know, how to stop...

Update textView in appWidget android doesnt work properly

android,textview,runnable,android-appwidget
i'm trying to create an appWidget with a timer and 2 button,(play and stop). The problem is that when i start the playButton the timerValue doesn't update. Probably is a stupid problem. This is my class Service: @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStart(intent, startId); productivityDB...

How to show alert dialog in a running thread using AsynctTask? [duplicate]

java,android,multithreading,android-asynctask,runnable
This question already has an answer here: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) [closed] 3 answers How can I show an AlertDialog using runnable Thread in doInBackground method, I'm using AsyncTask and I need to use a running thread to show a message that I receive from my API, but the dialog...

How to get a local variable from a Runnable Thread

java,android,multithreading,runnable
I have a helper (Not an activity) class that makes a query to an API which has a public function called run() and runs on a new thread (As per Android specifications). My MainActivity creates a new MakeQuery object and runs its run() function: MakeQuery q = new MakeQuery(); q.run();...

Calculate time thread android

java,android,multithreading,runnable,android-wallpaper
I'm using a thread to set an image as background and in this thread i have a dialog. The dialog starts and should be close when the wallpaper will be set. This is the code so far setWallbtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final ProgressDialog myPd_ring=ProgressDialog.show(SingleWall.this, "Setting...

Java - how to get the stack trace from before a Runnable?

java,multithreading,stack-trace,runnable
I had a close look at the SO "questions that may already have your answer" here and surprised not to find what I'm asking for... When an exception occurs in (for example) the EDT, or you just want to examine the stack for whatever reason, it's trivial to find the...

How to Cancel a AlertDialogue from another method?

android,alertdialog,runnable
I have an Alert Dialogue Box and I want it to be accessible from a runnable method. The goal is to cancel the dialogue box once it reaches a certain criteria. Below is the code for creating the AlertDialogue: public void perm_dialogue() { final WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); LayoutInflater li...

Runnable, Pause and Resume thread

java,android,runnable,onresume,onpause
my app is working fine but i cant figure out why my void run(); still runs in the background when i click the "home" button. I want my thread to pause the Thread onPause and start the thread again when onResume() i called! Cant figure out what im doing wrong!...

subclass of thread implementing Runnable interface

java,multithreading,oop,interface,runnable
It confuses me why a subclass of thread that implements a runnable interface doesn't force me to override the run method. Basically, when i create simple class that implements Runnable it forces me to override the run method. But when i made the ordinary class a subclass of thread, it...

Intentservice doesn't call runnable

android,accelerometer,runnable,intentservice
I have following code in intent service (I have to use intentservice) //TIME HANDLER Log.i("start", "start getting data acc & gps"); //Register listeners and start getting data // // ACC: onStartAcc(); // handle_lower.postDelayed(new Runnable() { @Override public void run() { Log.i("stop getting data", "STOP"); //Stop listeners // // ACC: onStopAcc();...

What is the best way to pass data to a Runnable? [closed]

java,android,multithreading,runnable
I generally write most of my code without worrying about threading and such, and get it working and debugged before trying to offload pieces to other threads. For me, the simplest way to do it is to break the function down into a Runnable or two. From there I can...

Java: Can an Observer be notified of changes through a hierarchy of observers?

java,observer-pattern,runnable,observable
So I have a few classes that are just Observers, another that is both an Observer and Observable, and a third that is just Observable. I want to be able to take the class that is both and notify some of the Observers that the class that is only Observable...

sendBroadcast thru UI or non-UI thread?

android,multithreading,runnable,android-runonuithread
Is it better (for performance) to send a broadcast (ACTION_APPWIDGET_UPDATE in my case), in a separate thread than the UI thread (a runnable)? Or is it acceptable practice to do so on the UI thread?

How To Convert extends Thread Class to Implement Runnable

android,multithreading,runnable
I found some sample code online for creating a puzzle and I noticed that they have a Thread class that extends Thread and does things such as monitor the state of the puzzle and even sets properties of the surface view that is used for the puzzle. I want to...

Problems with executing a runnable which updates UI every second

java,android,runnable
I'm trying to update the background of my buttons every second that the activity is running. Everything seems to work fine with the runnable, as the Logcat outputs the integers every second in these two lines : Log.d("randomint", Integer.toString(randomInt)); and Log.d("back", Integer.toString(back)); however I don't see any visual changes on...

View recycling in listview causes postDelayed() issue

android,runnable,android-handler,postdelayed
I have a list of user tasks/to-dos which have deadlines associated with it. Every minute on the minute I update the TextView that shows the time remaining for these task. The problem I have is that some times when the textview gets updated the wrong time remaining gets displayed, especially...

Thread Runnable vs AsyncTask Life Cycle

java,android,multithreading,android-asynctask,runnable
I would like to better understand what happens to a Thread or a AsyncTask when activity is destroyed. So in this scenario, a Thread or AsyncTask would be started from activity, and user hits home button and onDestroy gets called triggering GC before either Thread of AsyncTask had a chance...

Java Gui communication with serial port

java,swing,serial-port,runnable
I have Class, that receive and send information from serial port: public class Terminal implements Runnable { static LinkedList<String> receiver = new LinkedList<String>(); public Terminal() { //... } public String getReceivedMessage() { String data = receivedMessfges.removeFirst(); return data; } // Other function that perform connection to COM port // ......