I need to run two processes simultaneously.
I wrote the code:
public void starttwoprocessing () {
final Thread tworunprocessing = new Thread(new Runnable() {
public void run() {
FlashLight.onFlashResume();
handler.post(new Runnable() {
public void run() {
camera.takePicture(null, null, photoCallback);
}
});
}
});
tworunprocessing.start();
}
First start:
camera.takePicture(null, null, photoCallback);
The second:
FlashLight.onFlashResume();
After changing places with the same result.
In this case, I get the first shot and the flash is started later.
Thread.sleep(...); does not help
How to start simultaneously flash, and immediately take a picture?
Thanks
written like this:
public class Launcher
{
public void main(String args[]) throws IOException, InterruptedException
{
try {
Process[] proc = new Process[2];
proc[0] = new ProcessBuilder("FlashPreview.onFlashResumeStart()").start();
Thread.sleep(3000);
proc[1] = new ProcessBuilder("camera.takePicture(null, null, photoCallback)").start();
try {
Thread.sleep(3000);
}
catch (InterruptedException ex)
{
}
proc[0].destroy();
Thread.sleep(3000);
proc[1].destroy();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Called:
mk = new Launcher();
try {
mk.main(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something I'm doing wrong.
Does not work at all, no crash, but wrote in the log:07-05 16:38:58.217: W/System.err(30934): java.io.IOException: Error running exec(). Command: [FlashPreview.onFlashResumeStart()] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, SECONDARY_STORAGE=/storage/extSdCard:/storage/UsbDriveA:/storage/UsbDriveB:/storage/UsbDriveC:/storage/UsbDriveD:/storage/UsbDriveE:/storage/UsbDriveF, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/framework2.jar:/system/framework/framework_ext.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar:/system/framework/sec_edm.jar:/system/framework/seccamera.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,66560, VIBE_PIPE_PATH=/dev/pipes]
even using Threads your processes will runs after eche other. Using Threads means that second process no need to wait while first one is done. But easiest way how to fire two processes at the same time it is use timeout or ProcessBuilder
Also it can be good idea to run second process in first one. As for me it the best solution.
P.S. privet, ne chasto yvidiw zdes svoih s ykrainu)))
I have implemented the following:
class MyTask extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
FlashLight.onFlashResume();
}
#Override
protected Integer doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
camera.takePicture(null, null, photoCallback);
}
}
Related
I want to use JRuby to run Ruby scripts.
However, I'd like it so that if a script takes longer than t seconds, it will automatically be closed.
Here's my attempt:
ScriptingContainer ruby = new ScriptingContainer();
int t = 3;
new Thread() {
#Override
public void run() {
try {
Thread.sleep(t * 1000); // Timeout
System.out.println("Timeout passed.");
ruby.terminate(); // This has no effect?
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Object output = ruby.runScriptlet(scriptWithAnInfiniteLoop);
ruby.terminate(); // Terminate without timeout, at the end of the script
Here's an answer using the deprecated Thread.stop():
ScriptingContainer ruby = new ScriptingContainer();
int t = 5;
String script = content;
Thread runner = new Thread() {
#Override
public void run() {
try {
ruby.runScriptlet(script);
ruby.terminate(); // Close normally.
} catch (Exception e) {
ruby.terminate(); // Close if JRuby crashes.
}
}
};
Thread killer = new Thread() {
#Override
public void run() {
try {
Thread.sleep(t * 1000);
runner.stop();
ruby.terminate(); // Close forcefully.
} catch (Exception e) {}
}
};
runner.start();
killer.start();
See this article on why it is deprecated: https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Since I am using a deprecated method I won't mark this as an official answer.
I have a method in which I call another method that has a callback. I want to receive this callback before leaving my method. I saw some other posts in which latches are used. My code looks like this:
public void requestSecurityToken(<some params>){
final CountDownLatch latch = new CountDownLatch(1);
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
//TODO
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This doesn't work, the method is stuck in the await() function. What happens is that, the method immediately jumps to the await(), and doesn't go into the onRequestSuccess() or onRequestFailure() method again. I guess this is a concurency problem... Any ideas on how to fix this issue?
EDIT: Added the line of code where I create the latch.
When you are doing this
new RequestListener<Login>
You are passing an object to your function , which implements an interface.
That is why those methods are not getting called , those methods are called only when you get the request result (success or failure).
You can do this instead.
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
someFunction();
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
someFunction();
latch.countDown();
}
});
public void someFunction()[
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
As the title describes, I have a View class in which I need to reach out to get some data via TCP before I update the drawing. When I implemented this in my usual new Thread()...start() construction Eclipse whined at me about instantiating something new in an onDraw() method. In response to that, I reconfigured my thread as a class variable and I'm attempt to execute t.start() in the onDraw() loop.
However, there must be some thread baby-sitting I'm not aware about because my code is throwing an exception (java.lang.IllegalThreadStateException: Thread already started) when it attempts to start the thread the second time. The following is the current version of my code:
Thread t = new Thread()
{
public void run()
{
try
{
String st1 = getNetwork(); // Get network information
if (null != st1)
{
String[] st = st1.substring (st1.indexOf (' ') + 1, st1.length()).split (",+");
setNeighbors (st.length);
for (String s:st)
{
Log.e (TAG, s.trim());
String[] t1 = s.trim().split ("\\s+");
numbers.add (t1[0]);
addresses.add (t1[1]);
states.add (t1[2]);
}
}
}
catch (Exception ex)
{ }
finally
{
NetworkView.this.wait = false;
}
}
};
#Override
protected void onDraw (final Canvas canvas)
{
if (++drawCtr % 300 == 0)
{
this.wait = true;
t.start();
while (wait);
try
{
t.join();
}
catch (InterruptedException e) { }
}
update (canvas);
try { Thread.sleep (50); }
catch (InterruptedException e) { }
invalidate();
}
I get that the 2nd time around, my thread has already been started. How do I "reset" or "unstart" it for a 2nd attempt??
As Henry pointed out, my initial concept was a bad idea. A much more workable architecture was to have the TCP thread control the redraw, rather than having the redraw thread control the TCP data exchange, especially because there's no need (at least in my case) to redraw the screen between TCP updates. Hence, I implemented this thread in my View object's constructor:
(new Thread()
{
public void run()
{
while (looping)
{
try
{
// Get the important data via TCP (CAN'T be on the UI thread)
String st1 = tcpClient.getNetwork();
String st2 = tcpClient.getDiscovery();
}
catch (Exception ex)
{ }
finally
{
try
{
// Redraw the display (HAS TO be on the UI thread)
net.runOnUiThread (new Runnable()
{
#Override
public void run()
{
invalidate();
}
});
}
catch (Exception ex)
{ }
try { Thread.sleep (2000); }
catch (InterruptedException e) { }
}
}
}
}).start();
The key is the invalidate() call in the finally block (that needs to be run on the UI thread). That will update the screen based on the fresh new information.
I am using an actionListener to trigger an sequence of events and ultimatley this code is called:
public class ScriptManager {
public static Class currentScript;
private Object ScriptInstance;
public int State = 0;
// 0 = Not Running
// 1 = Running
// 2 = Paused
private Thread thread = new Thread() {
public void run() {
try {
currentScript.getMethod("run").invoke(ScriptInstance);
} catch(Exception e) {
e.printStackTrace();
}
}
};
public void runScript() {
try {
ScriptInstance = currentScript.newInstance();
new Thread(thread).start();
State = 1;
MainFrame.onPause();
} catch (Exception e) {
e.printStackTrace();
}
}
public void pauseScript() {
try {
thread.wait();
System.out.println("paused");
State = 2;
MainFrame.onPause();
} catch (Exception e) {
e.printStackTrace();
}
}
public void resumeScript() {
try {
thread.notify();
System.out.println("resumed");
State = 1;
MainFrame.onResume();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopScript() {
try {
thread.interrupt();
thread.join();
System.out.println("stopped");
State = 0;
MainFrame.onStop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The runnable is created and ran, however, the problem occurs when I try to use the any of the other methods, they lock my UI. (I'm assuming this is because im running this on the EDT) Does anyone know how to fix this?
That's not how you use wait and notify. They need to be executed on the thread that you are trying to pause and resume. Which means you need to send a message to the other thread somehow. There are various ways to do this, but the other thread needs to be listening for this message, or at least check for it occassionally.
...
Thread showWordThread = new Thread() {
public void run() {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
this.run();
}
};
showWordThread.run();
}
...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
But error still occured.
Others have explained that you should use a while loop instead. You're also trying to call the run method inside your anonymous class declaration. Additionally, you should call start, rather than run - when the new thread has started, it will call run automatically. I'd actually suggest implementing Runnable rather than extending Thread, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
#Override public void run() {
while (someCondition) {
try {
Thread.sleep(config.delayTime * 1000);
// Presumably do something useful here...
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
Alternatively, consider using a Timer or ScheduledExecutorService.
You are calling run method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow exception throws.
Maybe you want increasing Heap Size of JVM but this solution don't solve your problem and StackOverflow will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
public void run()
{
try
{
sleep(config.delayTime * 1000);
}
catch (Exception e)
{
System.out.println(e.toString());
}
// this.run(); this snnipet code make error
}
};
showWordThread.run();
}
Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while loop.
Thread showWordThread = new Thread() {
public void run() {
while(condition) {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
showWordThread.start();
}
Your code have infinity recursive, you should change the code to:
Thread showWordThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
};
showWordThread.start();
Your function calls itself each time you run it.
That results in a stack overflow.
Maybe because you call run method (this.run()) from itself?