Let's try a very small part of the problem first. See what this does for you: for(int i = 0; i < 10; i++ ) { Thread.currentThread().sleep(1000); System.out.println(i); } You found the Thread.sleep() method before, but this shows you can use it with much less effort. Now keep this loop and replace the print line with a call to a method ... |
IllegalMonitorStateException always means you've called either wait(), notify(), or notifyAll() on an object without being inside a block or method synchronized on that object. You're calling wait() and notify() on your Consumer and Producer Runnables, but you're never synchronizing on these objects -- hence the exceptions. But it doesn't seem like you understand how to use wait and notify -- do ... |
Hi, I have reader.java class file readResult extends Thread I am calling readResult from reader.java as follows: //pt.1 for (int i=0; i<10; i++) readResult rd = new readResult(); rd.start(); } //pt.2 I am doing some processing in run() method of readResult.java & setting a flag in run method in a while loop. What I want to do is: After pt.1 to ... |
Ideally, the run() method should only be called at the scheduled time... However... - The Timer class only uses one thread, so a TimerTask may be called late if another task is currently running. With enough repeating timer tasks, a backlog could even develop. - The Timer class uses the system time to calculate the wait times, so you can get ... |
i have a class that tests the function of threads.(no object of the class is involved) a short desc abt the class the class has: a counter(static, initialized to zero). a synchronized static method accessed by main() thread that increments the counter by one and sleeps for 20 sec. public synchronized static void setStatic(){ i=i+1; System.out.println("i before sleeping "+i); try{ Thread.sleep(20000);} ... |
Hallo to all, I have a burdensome problem: I have one servlet who is sterted at deploy and in his init() its created main thread which is supposed to run forewer. Her run() method should execute other threads which are created on demand from other class (or servlet). For this other child threads I had created class with schedule tasks (so ... |
Consider the code: class Foo ... ExecutorService executor; public void start() { startThis(); startThat(); } private void startThis() { executor.execute( new Runnable() { public void run() { ... } } ); } private void startThat() { executor.execute( new Runnable() { public void run() { ... } } ); } I want to ensure that the Runnable started in startThat() cannot run ... |
|
I have an application in which I have a set of objects, and I need to query them for a message in certain order, and then to transmit that message to all of the objects. For example, imagine there are 20 'objects' playing a game. So my application is in charge of querying the object whose turn it is, obtain his ... |
I have a xml file having schedules.. Looks like below.. usually the schedule is done for one full month at a time.. on a 'date' at the 'start' time a job starts (basically a video recording) and at 'end' the job stops. Currently ... |
The fact that the method is static is of little importance here. If the static method really does only use local variables, no object fields or methods, then it is thread-safe. If it accesses any object fields or methods, it may not be thread-safe, depending on what those fields or methods are used for, in other code. If you can cut ... |
You are presumably happy with the way that modern single-CPU computers give the illusion of doing more than one thing at once, in multi-processing. Your word processor, Web browser and e-mail all appear to be running at once, in separate processes. Threads achieve the illusion of simultaneous execution by very similar means to processes. The efforts of the CPU(s) are switched ... |
you can call run() directly but if you do that your run method will not execute in a seprate thread it will just execute in the thread from which you called it.... for eg in your program when you call t.run() run will be executed in the main thread (ie the thread calling your main method) and not in a seprate ... |
|
This implies to me that you can create a Runnable that returns a result and execute this Runnable (and obtain it's result) using the method above. But how do you create a Runnable that returns a result when this interface contains only a single run() method with a void return type? If someone could show a simple example, I'd really appreciate ... |
Yes. Calling run does not actually start a new thread - it executes the code within the current thread context (and thus blocks it until run finishes). Only calling start will actually start a new thread, and execute its runs method in a new concurrent context (and thus ensure that the current thread can continue running right away). |
|
Hello, I have am working on improving the efficiency of my sending queue, a small setup so a separate thread can send objects over a network - so that other threads can add an object to be sent to that thread's queue, and go on doing whatever else while the sending thread processes the queue. Currently, I have a system where ... |
Hi,we use the start() method of a thread instance to run the thread. (i know that we don't actually run the thread,but register it with the thread scheduler, and it calls the run method implicitly) but i cud run the thread by directly calling the run method. how is it possible ? and what is the use of start method then? ... |
|
|
|
Pardon my replication; I've posted a variant of this question on this board before, but now I understand the nature of my problem better, thus this post. Basically, I've got a program which creates a new thread from a class that extends Thread. The program instantiates an object of that class (successfully -- everything in the constructor works OK), and then ... |
|
|
|
Hello to everyone. I am newbie to java. I have a problem concerning threads. I havewritten some code that will read from an html file and extract information adn then update an excel spreadsheet. The problem I am now having is that I do not wish the thread to exit if there is an exception throw. Rather I wish for it ... |
A static variable can't be accessed from a non-static method. But we can access a static variable inside run() method. package com.pspl.thread; public class TestClass extends Thread { private static int threadcounter = 0; public void run() { threadcounter++; System.out.println(threadcounter); } public static void main(String[] args) throws Exception { for(int i=0; i<10; i++) { synchronized(TestClass.class) { new TestClass().start(); } } } ... |
Just to enumerate the common possibilities: 1. Use Unix/Linux cron and run the program under a batch script. Windows also has this ability, although the scheduler mechanism is different. 2. Set up a timer task thread (which you did). 3. Incorporate Quartz Scheduler and let it do cron-like functions. You'd normally only do this in the case where a long-running application ... |
How to make a particular thread to start among other threads of same priority? For example I have 5 threads T1, T2 ~ T5 and all are having same priority. How would I go, if I want to have the thread say T3 to execute first among T1 ~ T5. Thanks Murali Narain |
Java 1.5's CountDownLatch notwithstanding, I have a couple of questions about Ajay's solution: Couldn't Thread.join() be used instead of the wait()-notifyAll() approach? I mean, the 10th thread would attempt to join on each of the preceding 9 threads. Wouldn't that accomplish the desired result? Lastly, are there any reasons to prefer the wait()-notifyAll() approach over trying to join() on each of ... |
Hi everyone, I found some question and couldn't figure it out~ wonder if someone can shed some light on this ? I had some java code as following, it rans fine.... but when I tried to make it run for only 10 times, I modified the loop in Waiter's run method like this public void run() { for(; count < 10; ... |
|
Hi All, Probably I know that many of you might be asking me "Why" do I want to throw a checked exception from a run() method of a Thread (either by inheriting Thread or implementing Runnable), but I'm just curious if at all there is some way of capturing the exception, so that some thing meaning ful can be done instead ... |
public static void main(String[] args) throws Exception { fun (2); fun (4); fun (7); fun (6); for(int i =0 ; i<10000; i++) { StringBuffer sb = new StringBuffer(); sb.append("Run the other Threads first, please."); sb.append("Run the other Threads first, please."); sb.append("Run the other Threads first, please."); // Just a "load" to delay the execution of println()'s below } System.out.println(1); System.out.println(3); System.out.println(5); ... |
To be honest, I come to the same conclusion. The current thread starts this new thread. It should not block afterwards. However, this new thread needs to be limited in time. Using join on this thread from the current thread will block the current thread. To prevent that, the current thread starts two threads: - the timed thread - a thread ... |
|
i have seen peoples saying that start will call the run method and yes that is correct but partially main things is that. Start will create a new thread and that thread after initializing itself call run method. Internal implementation of run method, Runnable:- Runnable is a interface so it doesnot contain implementation of run method.So any class which implements this ... |
|
In my Java applet I want infinite number of enemys ships to pass from my top left corner and the ships will work like space invaders (ie come closer when hitting the side of applet). But I'm stuck on implementing the feat where infinite amount of ships would arrive in a set interval. The ship objects are added to an ArrayList, ... |
Hi Suppose If run a program , I am sure that JVM will create main thread to execute the program. But I would like that to know that internally how many threads JVM will create ?. I know that GC is daemon thread. So when it will create ?. Like GC , JVM will create any more threads ? Please let ... |
I have 1 object of the calling class which needs to be validated in the called class. this validation needs to be done in one of the threads of the called class so I need to pass a parameter (instance of calling class) to the run method of called class. How can I do this....or please can you suggest me some ... |
hi I am trying to work on an overloaded run method . eg:- I have a class userRunnable which implements the run and also gives definition for overloaded run ie public void run(long milliseconds ) {} now in my main i create a thread and want to invoke the overloaded run for my thread . can anyone explain how my thread ... |
I think Ragi is asking about the thread that called start(). There is no good reason to have this reference. There is no caller-callee relationship between threads. Not even a parent-child relationship like between the OS processed. One thread starts another and then may do whatever it pleases, including exiting. Having that reference would mean that if that thread exited, it ... |
class Job implements Runnable { public void run() { for(int i = 0 ; i<10 ; i++)System.out.println("run() " + "> <"); //run("demo"); } public void run(String s) { for(int i = 0 ; i<10 ; i++)System.out.println("run(String) " + s); } } public class Overload { public static void main(String [] args) { System.out.println("main thread !"); Job j1 = new Job(); Thread ... |
you can't start a stopped (completed/finished) thread as the thread state now says that it does not (cannot) execute (this is a restriction by JVM), however if you do want to reuse your threads.. you can use java.util.concurrent.ExecutorService threadPool = Executors.newFixedThreadPool(10); threadPool.execute(new Runnable(){ public void run(){ /// } } ); this will start a reusable thread, if you add more than ... |
Hello, Can anyone please answer this: Thread is a class which implements the runnable interface, so we override the run() method when we extend the Thread class and then call the start() method to actually run the thread. If I dont call the start() method and directly call run(), it will still execute ( without any "thread-ness" ). This part is ... |
Hi, I'm new to thread programming, and am kind of working on a monkey see monkey do approach. I have a reasonably sized program that runs multiple threads, and am wondering how to catch the runtime exceptions. The code below catches the runtime error and displays the message in a gui. I'm running the program in eclipse, and have noticed that ... |
What gives? package chatserver; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Rob */ public class ChatServer { int x[] = new int[4]; int y[] = new int[4]; BufferedReader reader; PrintWriter writer; /** * @param args the command line arguments */ public static void main(String[] args) { ... |
Hi Amey. Welcome to The Ranch! The reason it's not executing run is that you never tell it to. You never create a DemoThreadAlive object and pass it to the Thread. You're simply creating an empty Thread and starting that. I don't understand your second question, sorry - you can add stuff below the start() call if you want it to ... |
class Timer extends Thread { private int _delay; private TimerListener _listener; public Timer(int delay, TimerListener listener) { _delay = delay; _listener = listener; } public void run() { try { sleep(_delay); } catch (Exception ex) { ex.printStackTrace();} _listener.executedMethod(); } } interface TimerListener { public abstract void executedMethod(); } // cration du timer : Timer timer = new Timer(500, new TimerListener() { ... |
Hi everyone. I just wrote a small example about how to create threads but they just can't work as I expected. This program has two threads. Each thread do the same thing: they show a name and a number. What I was expecting is these two threads run at the same time, I mean, I could see some outputs from the ... |
/* A Method called Factorial * Using perimater in Main function * to pass some variable to Factorial * Return a Factorial Vaule to main */ public class FactorialMath{ private static final int MAX_Num=4; // What is 4! (4*3*2*1) public void main(String[] args){ for (int i=0; i |
frontrunner, Its dead easy because C and E are the only ones that use the start() method required to execute the run method in a thread which in turn executes the doStuff method. The others are wrong for other reasons but that doesnt even matter because even if they where correct they wouldnt start, only create the thread. Regards, Ken |
Your question, as mentioned is very poor, but as wild stab in the dark you should make sure that you are running on real Java as provided by Sun and not the abortion that lives that is gcj aka fake Java. One of the many ugly problems in gcj the last time I tried it was that threading was VERY broken. ... |
#ofCPUs*(#ofThreads/CPU) will give you how many concurrent threads your system will support. Active CPU time is a limited resource and when you start threads they all go into the scheduler and vie for active CPU time. So realistically they really don't simultaniously run, but if you are not watching nor have sequence specific tasks, then it looks like they are. If ... |
I never quite grasped the concept of threads except that's what I'm constantly told to use. I want to run a function receive() constantly in the background while everything else is running. I have Thread t = new Thread(receive()); t.start(); I get a "Void type not allowed here "compilation error. Help would be very much appreciated. |
|
|
|
You can't find one what? One documentation on Thread? One tutorial about it? Google "java Thread" and among the first few hits should be both a link to the Java concurrency trail and a link to the Thread documentation page. In fact, one of them will probably be the very first hit from google with that query and the other will ... |
I know that an interface contains only method declaration and no body. I read that a thread starts it work when it encounters the run() method. If run() is a method in an interface named Runnable, how does the compiler get to know that the function implies that the thread is supposed do some work. Because the run() function that you ... |
hmmm... I think I understand... create one instance of Timer in my Executer instance create one instance of TimerTask in my Executer instance, define it as simply "setPause(false)" when I receive my "pauseEvent": - setPause(true) directly in my Executer instance - schedule the "setPause(false)" TimerTask for execution in 100ms I think that should do it, now I need to check performances... ... |
|
Your example does not explain your question. If you have two threads than there are a number of ways you can pass data between them. A queue is one way. Using a queue evolves into a task queue which the java API provides in one of the APIs. If you just want to pass a string then 1. Create a class ... |
|
i have a task to display the splashscreen when system time is equal to given specified time. i have code to display splashscreen and code for system time.but iwant code to run my program continusely using threads so that i can display at any specified time by comparing it.could some ome please help me |
run method of Base calss is executing when I run this code. If I remove Base.run() it Test1.run() is getting executed. can anybody explain why.? class Base extends Thread{ public native String getTime(); Base(Runnable r) { super(r); } public void run() { System.err.println("In Base"); } } public class Test1 implements Runnable { boolean bStop; public static void main(String argv[]){ Test1 m ... |
Please check this link: [http://java.sun.com/developer/EJTechTips/2003/tt0825.html|http://java.sun.com/developer/EJTechTips/2003/tt0825.html] Under APPLICATION INITIALIZATION USING LISTENERS it says: "When a Web application is deployed, the Web container initializes its ServletContext object. If the Web application's deployment descriptor declares any ServletContextListeners, the container calls each listener's contextInitialized method, in the order that the listeners are declared. This event occurs only once in the servlet's life cycle: before any ... |
|
I am currently running a 2 threads against the same java .jar program on my own machine with each thread sending different parameters to this program which splits the programs up so that they run in parallel. I would like to be able to do the same thing except instead of running these 2 programs on my own machine I would ... |
/** * When an object implementing interface Runnable is used * to create a thread, starting the thread causes the object's * run method to be called in that separately executing * thread. * * The general contract of the method run is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ |
Currently, I have a "main" thread which the user can input commands into, and another thread which occasionally runs in the background. When I want something to run in the background, I just create a new thread. However, I figured it'd be more efficient to have one thread running in the background to do something as opposed to spawning hundreds of ... |
|
I'm trying to install netbeans 5.0 Win XP SP2. I've installed J2SE 1.4.2_11. I added the the bin folder where javac etc. is to the path but still I get the NoClassDefFoundError. This happens on all the computers I try to install it to. M friends get the same error. Please help Koos |
Hi All I need to make a thread which can run on regular interval say(every 15 mins..eveyday..) i want this thread excuted as soon as my server (tomacat 4.0) will start with my appication. i heared something abt Times class but don't know how to implemet it.. Plz help Thanx In Advance |
|
|
You are making a very common Swing mistake. Event callbacks like mouse click listeners should not wait, sleep, join or the like, they need to return promptly. Until they do no graphics updates will have any effect. This is because the event listeners and the graphics updates all take place on the same thread (the dispatcher thread). Start the thread and ... |
|
no no Buddy , my question was not confine to any of the peticular OS.....i m takin about in general.............that Without OS support its possible to have Multi threading in java.....?? if OS doesnt provide the this feature......did JVM is still capable to provide the multi-Threading @ this time.... thax for Anticipation..........reply me back i wlll be thankful to you....as i ... |
This might seem like a fairly silly question, but if you have a class that extends Thread and implements runnable, is public void run() the only method of that class that will run parallel to the calling class or will any of the methods in the thread class run in parallel with the calling class? Interested to know as this is ... |
I'm trying to build an client-server application where users may login to access their files on the server. The server application runs on a linux server. When a user connect to the server using ssl a new thread is started at the server. The user enters username, the client application send the username to the server, the serverthread checks /etc/shadow and ... |
HI, I am getting the below error while trying to run my webapplication. Here I am calling a Java class from a diff package which is using same datasource. The function filter returns type is void and in that function when i execute the second resultset i get this error, though the SQL executing is fine. java.lang.NullPointerException at org.report.generator.MainClass.filter(MainClass.java:70) at org.report.ovsd.reportGeneration.processRequest(reportGeneration.java:43) ... |
On my old windows the thread does seem to work, it's a framerate class and it creates a new thread and then runs indefinitely, constantly repainting the applet. However, when I ran it on my new mac ibook it doesn't work. I tested it by using a showStatus in the initiator of the class and that didn't even show - which ... |
|
Yes we know what ASAP means. It is not appreciated when people use ASAP or URGENT in their posts. We are not your slaves and not matter how urgent you think it is we are not going to drop everything to give you an answer. Also I am not going to revert. I like being a fish! |
We declare a method as synchronized so that it is sequentially accessed in a multithreaded environment. Lets take an example public class ThreadDemo extends Thread { public static void main(String [] args) { ThreadDemo t1 = new ThreadDemo(); ThreadDemo t2 = new ThreadDemo(); t1.start(); t2.start(); } public synchronized void run() { for(int i=0;i<10;i++) { System.out.println("Thread-" + Thread.currentThread().getName() + i); } } ... |
- I made a small Runnable brute force sudoku board generator - I start the runnable & I measure it's performance in "million boards per second" (mbps for this discussion) - I get an avg of about 52 mbps (core2duo 2ghz, 1 core maxed, other idle) - I can run 2 instances of this java program and the performance per-program will ... |