In my code:
public class thread1 implements Runnable {
public static void main(String[] args) {
thread1 d = new thread1();
new Thread(d).start();
Thread t1 = new Thread(d);
t1.start();
}
#Override
public void run() {
for (int i = 0; i < 3; i++) {
sleep1();
sleep2();
}
}
void sleep1() {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized void sleep2() {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I ran my code and calculate its running time to finished.
The minimum time to finished was 7 seconds.
Why?
It should be 6 seconds, Because
3loops * 2seconds = 6seconds.
Because of context switching. sleep() is not a guaranteed amount of time, but is subject to other things going on in the system. It will try to come back, but may not succeed. Also, probably rounding in your IDE.
Program running time also accountable. You have put 6 secs to thread sleep. So Next thread will be executed. So context switching takes place.
Related
I just started java and I am trying to learn java as much as possible. I was trying to solve a problem but couldn't get the right solution. I have tried this program according to my own logic, ended in failure. Looking forwards for someone's guidence.
public class ThreadDemo implements Runnable
{
Thread t;
ThreadDemo()
{
t=new Thread(this,"Child");
t.start();
}
public void run()
{
try
{
Thread.sleep(2000);
}
catch (Exception ex){}
}
public static void main(String[] args)
{
ThreadDemo td=new ThreadDemo();
Thread t1=Thread.currentThread();
t1.setName("prime");
try
{
for(int i=0;;i++)
{
if(i!=0&&i!=1&& i%i ==1 && i%2!=0)
{
Thread.sleep(1);
System.out.println(i + "j");
}
}
}
catch (Exception ex){}
}
}
I think you are trying to learn to use threads by implementing a function that calculate primies in 10 senconds. In other words, you want to stop the prime number calculation after 10 seconds by multithreading. So you could set a flag in the prime calculation loop to make it stop, and then in another thread make it change after 10 seconds.
By the way, your way of calculating prime numbers is incorrect. I show you the core that printing numbers as many as posible in 10 senconds. You can modify the code to print prime numbers》
public class ThreadDemo implements Runnable {
Thread t;
static boolean flag = true;
ThreadDemo() {
t = new Thread(this, "Child");
t.start();
}
public void run() {
try {
Thread.sleep(10_000);
flag = false;
} catch (Exception ex) {
}
}
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
Thread t1 = Thread.currentThread();
t1.setName("prime");
try {
for (int i = 0; flag; i++) {
System.out.println(i);
Thread.sleep(1);
}
} catch (Exception ex) {
}
}
}
SOLVED: Sorry, problem had nothing to do with Java Threads. C3P0's ComboPooledDataSource was creating so many threads and not releasing them. After switching to DBCP2's BasicDataSource, the thread count doesn't go up anymore.
I wrote a web app and it crashes due to not able to create anymore threads. In one of the function, I have the ExecutorService creating a thread pool of 10 threads as a local variable of that function. When I monitor the threads, every time the function is called, about ~12 threads are getting created.
I then moved it to a test file and run this in multiple shells:
public static void main(String[] args) throws Exception {
testRun();
Thread.sleep(1253234234);
}
public static testRun() {
WorkQueue queue = new ThreadPool(10);
for (int i = 0; i < 10; i++) {
queue.addJob(new Runnable() {
#Override
public void run() {
System.out.println(this);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
}
queue.startJobs();
queue.wait(10);
}
public void wait(int seconds) {
executor.shutdown();
try {
if (!executor.awaitTermination(seconds, TimeUnit.SECONDS)) {
throw new RuntimeException("Thread pool terminated unexpectedly due to time out.");
}
} catch (InterruptedException ie) {
throw new RuntimeException("Thread interrupt event is received while waiting for termination of ThreadPool - " + ie.getMessage());
}
}
This creates 25 threads in every shell, then release only 10 after it's done. So every time this function is called, there're 15 threads that are not getting released. I'm going to guess the 15 is the maxPoolSize, and the 10 is the corePoolSize. But why aren't they all getting released when function finished?
So I thought maybe I'm not understanding this ExecutorService class and write the raw thread:
public static void main(String[] args) throws Exception {
testRun();
Thread.sleep(1253234234);
}
private static void testRun() throws Exception {
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
System.out.println(this);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
}
These now creates 27 threads for every shell and release 10 after each function finished. What am I doing wrong? How do I release these threads local to a function? Can someone point me to the right way?
Please ignore compile/syntax error as I replaced the test content after testing it, so this isn't copy and paste off of working code.
Thank you.
consider this code which basically has an object(WaitedObject) and two threads(SomeTask and SomeTaskWithWait) compete to call the methods (longRunningTask() and withWaitTask() respectively) of the object synchronously
package closerLookAtWait;
class WaitedObject
{
int i=0;
synchronized void longRunningTask()
{
System.out.println(i++);
for(long j=999; j>0; j--)
{}
}
synchronized void withWaitTask()
{
System.out.println("Now Waiting");
long time1 = System.currentTimeMillis();
try {
//Thread.sleep(500);
wait(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long time2 = System.currentTimeMillis() - time1;
System.out.println("Done Waiting for "+time2);
}
}
class SomeTask implements Runnable
{
WaitedObject wo;
SomeTask(WaitedObject wo)
{
this.wo = wo;
}
#Override
public void run() {
while(true)
wo.longRunningTask();
}
}
class SomeTaskWithWait implements Runnable{
WaitedObject wo;
SomeTaskWithWait(WaitedObject wo)
{
this.wo = wo;
}
#Override
public void run() {
while(true)
wo.withWaitTask();
}
}
public class SomeWaitingWithLong {
public static void main(String[] args) {
WaitedObject wo = new WaitedObject();
new Thread(new SomeTask(wo)).start();
new Thread(new SomeTaskWithWait(wo)).start();
}
}
sample output:
well i got output as 54,54,50,65,51,52,..,78,..84,..50,52,52.
now my question is why such inaccuracy? (even 65 is ok, but why 84?)
One of the reasons is, OS puts that thread in suspended mode for the time(ms) you provide in wait(). When the time completes it isn't guarrented that your thread will be executed at once because OS has assigned another thread with a higher priority in your process to be executed by the processor or some other higher priority process is being assigned to the processor for execution. Even if your thread was at highest priority, even then there will be some delay sometimes because of context switching & in Java's case, GC.
Simple answer: Android is not a real time OS.
Sorry if the question is quite simple. I am a beginner.
I have to create thread that calulates something, while the first thread works the other one have to measure if the first thread calculate the function in specified time. If not, it has to throw exception. Else it returns the answer.
I'd take the java.util.concurrent components - simple example
public void myMethod() {
// select some executor strategy
ExecutorService executor = Executors.newFixedThreadPool(1);
Future f = executor.submit(new Runnable() {
#Override
public void run() {
heresTheMethodToBeExecuted();
}
});
try {
f.get(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// do something clever
} catch (ExecutionException e) {
// do something clever
} catch (TimeoutException e) {
// do something clever
}
}
Have your thread notify a synchronization object when it is done and have your other thread wait x number of milliseconds for it to finish.
public class Main {
private static final Object mThreadLock = new Object();
static class DoTaskThread extends Thread {
public void run() {
try {
int wait = new Random().nextInt(10000);
System.out.println("Waiting " + wait + " ms");
Thread.sleep(wait);
} catch (InterruptedException ex) {
}
synchronized (mThreadLock) {
mThreadLock.notifyAll();
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
synchronized (mThreadLock) {
DoTaskThread thread = new DoTaskThread();
thread.start();
try {
// Only wait 2 seconds for the thread to finish
mThreadLock.wait(2000);
} catch (InterruptedException ex) {
}
if (thread.isAlive()) {
throw new RuntimeException("thread took too long");
} else {
System.out.println("Thread finished in time");
}
}
}
}
join is a lot simpler than using a lock.
join (millis)
Waits at most millis milliseconds
for this thread to die. A timeout of 0
means to wait forever.
Example code:
Thread calcThread = new Thread(new Runnable(){
#Override
public void run() {
//some calculation
}
});
calcThread.start();
//wait at most 2secs for the calcThread to finish.
calcThread.join(2000);
//throw an exception if the calcThread hasn't completed.
if(calcThread.isAlive()){
throw new SomeException("calcThread is still running!");
}
Have a look at http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit) which allows you to handle this without dealing with thread synchronization yourself.
I am going through the kathy sierra SCJP 1.5 Chapter 9(threads) and there it is mentioned as:
Notice that the sleep() method can throw a checked InterruptedException
(you'll usually know if that is a possibility, since another thread has to explicitly do
the interrupting), so you must acknowledge the exception with a handle or declare
I just need a sample program to know when it happens (which i can run on my machine)?
I googled but could not find any sample code to test this functionality..
Thanks in Advance
Here's an example:
public class Test
{
public static void main (String[] args)
{
final Thread mainThread = Thread.currentThread();
Thread interruptingThread = new Thread(new Runnable() {
#Override public void run() {
// Let the main thread start to sleep
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
mainThread.interrupt();
}
});
interruptingThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}
To walk through it:
Set up a new thread which will sleep for a short time, then interrupt the main thread
Start that new thread
Sleep for a long-ish time (in the main thread)
Print out a diagnostic method when we're interrupted (again, in the main thread)
The sleep in the main thread isn't strictly necessary, but it means that the main thread does get to really start sleeping before it's interrupted.
public class SleepTest1 extends Thread {
#Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
Thread.currentThread().interrupt();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepTest1 st1 = new SleepTest1();
st1.start();
}
}