I made a concurrency class to test out threads. since I wanted to find out the best way to run threads at the same time.
I am surprised by my results:
test
test
Othertest
test
Othertest
test
test
test
The results I expected were for the threads to come back randomly yet they seem to come back consistently in the same order! Does anyone know why? Does this mean that they are not running concurrently? How might I go about getting them to run at the same time?
Here is my code:
public class ThreadTest {
public static void main(String args[]) throws InterruptedException
{
new Thread(new ThreadTest().test()).start();
new Thread(new ThreadTest().test()).start();
new Thread(new ThreadTest().otherTest()).start();
new Thread(new ThreadTest().test()).start();
new Thread(new ThreadTest().otherTest()).start();
new Thread(new ThreadTest().test()).start();
new Thread(new ThreadTest().test()).start();
new Thread(new ThreadTest().test()).start();
}
public Runnable test() throws InterruptedException{
Thread.sleep((long) (Math.random()*1000));
System.out.println("test");
return null;
}
public Runnable otherTest() throws InterruptedException{
Thread.sleep((long) (Math.random()*1000));
System.out.println("Othertest");
return null;
}
}
The Thread constructor accepts a Runnable on which the Thread will eventually execute the run() method. Right now you aren't returning a Runnable object. you are returning null. So the execution you do in your test() and otherTest() methods is executed synchronously.
All your execution happens in one thread. This
new Thread(new ThreadTest().test()).start();
executes test(), sleeps for a second, prints "test" and returns null. The start() call doesn't do anything because the Runnable is null. This continues for each other call you do.
You need to put everything in your test() and otherTest() methods inside a Runnable#run() method. For example
new Thread(new Runnable() {
public void run() {
Thread.sleep((long) (Math.random()*1000));
System.out.println("test");
}
}).start();
Consider the source code of the run() method of Thread class, which is executed when start() is called
#Override
public void run() {
if (target != null) {
target.run();
}
}
Where target is the Runnable reference you pass in the constructor. Obviously, if it is null, it won't do anything.
I think you might have better luck with this:
public class ThreadTest {
public static void main(String args[]) throws InterruptedException
{
new Thread(test).start();
new Thread(test).start();
new Thread(otherTest).start();
new Thread(test).start();
new Thread(otherTest).start();
new Thread(test).start();
new Thread(test).start();
new Thread(test).start();
}
public static Runnable test = new Runnable() {
#Override
public void run() {
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("test");
}
};
public static Runnable otherTest = new Runnable() {
#Override
public void run(){
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Othertest");
}
};
}
The idea is to pass an instance of Runnable as an argument to the Thread constructor. You are not really doing that, because test() and otherTest() are both returning null. The above code shows one way of running the threads in the way that I'm guessing you want. Other approaches are certainly possible.
You need to implement your test and otherTest methods as Runnable implementations. Like so:
private static class Test implements Runnable {
#Override
public void run() {
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println("test");
}
}
private static class OtherTest implements Runnable {
#Override
public void run() {
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println("Othertest");
}
}
public static void main(String args[]) {
new Thread(new Test()).start();
new Thread(new Test()).start();
new Thread(new OtherTest()).start();
new Thread(new Test()).start();
new Thread(new OtherTest()).start();
new Thread(new Test()).start();
new Thread(new Test()).start();
new Thread(new Test()).start();
}
You could, of course, try to reduce the duplication a little:
private enum Runnables implements Runnable {
TEST {
#Override
public void run() {
if (!sleep()) return;
System.out.println("test");
}
},
OTHER_TEST {
#Override
public void run() {
if (!sleep()) return;
System.out.println("Othertest");
}
};
static boolean sleep() {
try {
Thread.sleep((long) (Math.random()*1000));
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
}
public static void main(String args[]) {
new Thread(Runnables.TEST).start();
new Thread(Runnables.TEST).start();
new Thread(Runnables.OTHER_TEST).start();
new Thread(Runnables.TEST).start();
new Thread(Runnables.OTHER_TEST).start();
new Thread(Runnables.TEST).start();
new Thread(Runnables.TEST).start();
new Thread(Runnables.TEST).start();
}
Your Thread implementation is WRONG.
You should either implement Runnable and implement run() method or
you should extend Thread class and override run() method.
What is happening is that your test() method or otherTest() is being called just as any method calls. And since you don't have any run() method your Thread.start() wont simply run anything.
Try changing your method like below.
public Runnable test() {
return new Runnable() {
#Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
public Runnable otherTest() {
System.out.println("Othertest");
return new Runnable() {
#Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Othertest");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
Related
i am generating a random string for infinite time and setting it to a EditText.
when i was not using runOnUi app was working on newer devices which have high capability. but it crashes on older model when i start the thread and gave error(called from wrong thread exception)
Then i used runOnUi but it makes the super slow and force close it.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
tryPass.setText(getAlphaNumericString());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
});
thread.start();
You're trying to block UI thread by calling Thread.sleep(2000); on UI thread.
Try this way:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tryPass.setText(getAlphaNumericString());
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
I have a sub class of RecursiveTask which contains a Runnable object and should execute it.The problem is that the code inside the run method never gets reached although I use ForkJoinPool.execute in order to not block the main thread.
public class test {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Display.getDefault().syncExec(new Runnable() {
#Override
public void run() {
System.out.println("lo");
}
});
}
};
ATLockTask t = new ATLockTask();
t.runnable = r;
new ForkJoinPool().execute(t);
}
}
public class ATLockTask extends RecursiveTask<Object>{
public Runnable runnable;
#Override
protected Object compute() {
try {
runnable.run();
} catch (Exception e) {
logger.catching(e);
}
return null;
}
}
How can I implement a timer in Java 8? I prefer one simple method for this. I want to do something every 15 min or 30 min. Any idea?
you can use
Thread.sleep(milliseconds)
call the function you want and put it inside Runnable .
Example :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000); // 3
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//your Function
}
});
}
}).start();
OR
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}});
t.start();
I am trying to learn about thread and find some examples in the internet. This is a java class that output "hello, world" every 3 seconds. But I have a feeling that the part about creating a Runable object is redundant.
Instead of writing
Runnable r = new Runnable(){ public void run(){...some actions...}};
Can I put the method run() somewhere else for easy reading?
This is what I have:
public class TickTock extends Thread {
public static void main (String[] arg){
Runnable r = new Runnable(){
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
};
Thread thr = new Thread(r);
thr.start();
}
And this is what I want to accomplish
public static void main (String[] arg){
Runnable r = new Runnable() //so no run() method here,
//but where should I put run()
Thread thr = new Thread(r);
thr.start();
}
Can I put the method run() somewhere else for easy reading?
Yes you could create your own runnable like this
public class CustomRunnable implements Runnable{
// put run here
}
and then
Runnable r = new CustomRunnable () ;
Thread thr = new Thread(r);
From the Java threads tutorial, you can use a slightly different style:
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Just make your anonymous Runnable class an inner static class, like so:
public class TickTock {
public static void main (String[] arg){
Thread thr = new Thread(new MyRunnable());
thr.start();
}
private static class MyRunnable implements Runnable {
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}
}
Or since TickTock already extends Thread in your example code, you can just override its run method:
public class TickTock extends Thread {
public static void main (String[] arg){
Thread thr = new TickTock();
thr.start();
}
#Override
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}
Thread thread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yippi);
final Handler hn=new Handler();
final TextView text=(TextView)findViewById(R.id.TextView01);
final Runnable r = new Runnable()
{
public void run()
{
text.settext("hi");
}
};
thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1750);
hn.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
thread.stop();}
The code here. I can not stop the runnable thread. Also, thread.stop() and thread.destroy() are deprecated. Can somebody help me? And also I don't understand how to stop the thread with the thread.interrupt() method. What's wrong?
The JavaDoc for Thread.stop() lists the following article as explanation for why stop() is deprecated: http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).
interrupt() is more suitable to stop some Thread from waiting for something, that is probably not coming anymore. If you want to end the thread, it's best to let its run() method return.
Create a boolean variable to stop the thread and use it in while(boolean) instead of while(true).
You can use Thread.interrupt() to trigger the InterruptedException within your thread. I've added code below that demonstrates the behavior. The mainThread is where your code would be and the timer Thread is just used to demonstrate delayed triggering of the interrupt.
public class Test {
public static void main(String[] args) {
final Thread mainThread = new Thread() {
#Override
public void run() {
boolean continueExecution = true;
while (continueExecution) {
try {
sleep(100);
System.out.println("Executing");
} catch (InterruptedException e) {
continueExecution = false;
}
}
}
};
mainThread.start();
Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping recurring execution");
mainThread.interrupt();
}
};
timer.start();
}
}
You can use interrupt method of Thread to try stop a thread, like below code.
May be it`s useful to you.
public class InterruptThread {
public static void main(String args[]){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
System.out.println("Thread is Runing......");
sleep(1000);
}
} catch (InterruptedException e) {
// restore interrupted status
System.out.println("Thread is interrupting");
Thread.currentThread().interrupt();
}
}
};
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Will Interrupt thread");
thread.interrupt();
}
}