Thread questions

Hi,
Here are my Thread questions:
Q.1 I don't understand interrupt() and internal flag and when should I use it?
Q.2 What does "No thread can make another thread yield" mean?
Q.3 Given:
public class MyRunnable implements Runnable
     public void run()
          //some code here
What is the proper way to create and start this thread?
Ans: new Thread(new MyRunnable()).start();
Why does it need to add new Thread as prefix?
Q.4 Given:
public class MyT extends Thread
     public void run()
          try
               for(int i=1; i<5; i++)
                    System.out.print(i + " ");
                    if(i>2)
                    interrupt();
                    sleep(1000);
                    if(interrupted())
                    break;
          catch(InterruptedException e)
               System.out.print("Caught");
Assume another object creates an instance of this Thread and starts it. Why does the outcome is:
1 2 3 caught
Thanks
gogo

You can find a lot of answers to your questions in the java tutorial.
http://java.sun.com/tutorial

Similar Messages

  • Plzzz write prog to this simple java threads question

    Write a program in C to create four processes. The original processes creates
    two children before it prints out "PARENT". The children processes print
    "CHILD1" and "CHILD2" respectively. The first child process creates a child
    process that prints out "GRANDCHILD".
    Note: The output must be guaranteed to print out in the following order each
    time it is executed:
    GRANDCHILD
    CHILD2
    CHILD1
    PARENT
    a. Write the program using C or C++ and forks to create the children processes.
    b. Write a second program using Java and Threads for the children processes.
    The output statements for CHILD1, CHILD2 and GRANDCHILD must come from print
    statements in the run method of the thread.

    Most people here will not do your homework for you. If you post a reasonable question that shows you've made some effort, and what the results of that effort were, and provides details about what parts you're having trouble with, then somebody will probably provide guidance so that [you can complete the work.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • HttpServlet thread question

    I am trying the understand the multithreaded nature of servlets and a thread's impact when invoking a static method. Any help in this matter would be greatly appreciated.
    It is my understanding that an HttpServlet object is instantianted once but is thread safe for concurrent requests. If the following servlet invokes a static method that contains local variables, will that static method need to be synchronized?
    For example,
    public class MyServlet extends HttpServlet {
    &nbsp&nbsppublic void doPost(...) {
    &nbsp&nbsp&nbsp&nbspStaticClass.myStaticMethod(request);
    &nbsp&nbsp}
    public class StaticClass {
    &nbsp&nbsppublic static void myStaticMethod(HttpServletRequest request) {
    &nbsp&nbsp&nbsp&nbspHttpSession session = request.getSession(); // is this a problem??
    &nbsp&nbsp&nbsp&nbspCallAnotherMethod(session);
    &nbsp&nbsp}
    I realize I could pass in the session instead of the request to avoid the local allocation, but I am trying to understand the implications of a static method allocating local variables as they pertain to multiple threads.
    One more observation is if I rewrite the above as below (i.e. not allocating the local session object) would this avoid the problem stated above (if one exists). In other words, would Java create a temporary local variable for the nested call within the CallAnotherMethod() below (which would be similar to the above scenario) or would it use a local register or the calling thread's stack space ( which I assume would avoid the issue above) ?
    public class StaticClass {
    &nbsp&nbsppublic static void myStaticMethod(HttpServletRequest request) {
    &nbsp&nbsp&nbsp&nbspCallAnotherMethod(request.getSession());
    &nbsp&nbsp}
    thanks for any help in advance,
    kevin

    Each thread has its own copy of local variables, so you don't have to synchronize a method call just to protect access to local variables. That is true whether the method call is static or not, and it is true whether the thread is a servlet or not. However, you may need to synchronize the call for other reasons. And therefore your question about "CallAnotherMethod(request.getSession());" is irrelevant.
    And by the way, this statement:
    It is my understanding that an HttpServlet object is instantianted once but is thread safe for concurrent requests. is not correct. An HttpServlet is not threadsafe; you are responsible for managing possible interactions between concurrent requests to the servlet.

  • Threads Question/Opinion

    I am currently developing an application that will create a process. The process itself will be cmd.exe with parameters. The application is Swing based and so I don't lock the event dispatch thread, I created a thread that will create the process. I also know that when using cmd.exe it is important to handle the inputstream and errorstream so the whole process does not lock. The examples I've seen for handling these streams where handled in threads of their own so they could be processed at the same time. My question is this: In your opinion would it be better to handle the process and streams in one thread, or should I create one thread to create the process and 2 threads to handle the streams (1 thread for each stream)? I think the multiple threads (essentially 3 for one process) will negatively impact the applications performance, but I don't know if handling the streams in a function/method within one thread would be adequate enough to keep the app from deadlocking. Any ideas?

    I had read that multiple threads can cause more
    e overhead and slow performance of the application in
    general. The article just said more threads=more
    overhead, Fair enough. That's true as far as it goes, but I can't imagine 3 threads ever causing any detectable problem, unless each thread is something like this public void run() {
        someField_++;
        Thread.yield();
    } It's not uncommon to have tens of threads, and I've created thousands in little dummy test programs and not noticed performance problems.
    I didn't have an exact number to work with
    and that was my concern. I believe the threads I was
    thinking of would perform the needed actions quickly
    and therefore not impact performance too much, but I
    wanted to be sure. The key is that each thead does enough at one time so that the overhead of switching is small compared to the work done, but also making sure that no thread hogs the CPU for too long. If you're doing I/O, then each call to read has the potential to let another thread have a turn, I believe. Otherwise it's common to put a call to yield in your thread's main loop. Maybe every iteration, maybe every 10 or 100 or whatever, depending on what that iteration does.
    If you have tasks that can be handled in parallel--indpendently of one another--or should be independent to prevent one from forcing another to wait (like reading two streams) then you should give those tasks separate threads. Once you have that working correctly, then if you have measured performance problems relating to how those threads interact or take turns (or don't take turns) then you can tweak the code to try to optimize that aspect of it.
    I am teaching myself Java and its
    been a bit of a haul. I appreciate the help and
    information I get from these forums hence this
    posting.Cool. Glad to be of help.

  • Simple threads question (I think)

    I searched all over the forum, but wasn't able to find an answer for this question, so here it is:
    I simply wanna slow down execution of a loop. I'm been playing with threads to try and do this using wait(long) but I always get the current thread not owner exception...
    Same thing when I tried it with Runtime.wait(long) or System.wait(long). Can anyone offer any suggestions?

    I simply wanna slow down execution of a loop. To do this, use Thread.sleep:
    //start doing something
    try {
      Thread.sleep(100);
    catch (InterruptedException e) {}
    //carry on doing somethingThe above code will cause the currently executing thread to go to sleep for 100 milliseconds (It will actually sleep for an arbitrary time of at least 100ms, so you can't use it as a timer, but for slowing something down, it'll do the job fine).
    I'm
    been playing with threads to try and do this using
    wait(long) but I always get the current thread not
    owner exception...Using wait if you don't properly understand it is a very bad idea. It is used when you need an object to be in some consistent state before continuing execution: The current thread waits for some other thread to change the object's state and notify it that a change has been made, before waking up and re-checking the object's state (This isn't all done by the wait method alone, but this is the situation in which you would use it). If you don't know how to use it properly, you are likely to cause a deadlock or contention problem.
    You are getting the error because when you call an object's wait method, you must first own that object's lock (i.e. be inside a block of code that is synchronized on that object). When a thread calls wait, the object adds it to its pool of waiting threads, and when notify (or notifyAll) is called on the object, it wakes up one (or all) of the threads in its waiting thread pool. The newly wawoken thread(s) then go into the ready state and try to get the lock back before continuing execution.
    The long argument to wait is a (non-strict) maximum time that the thread should wait for before it wakes up anyway, whether or not notify has been called.
    Same thing when I tried it with Runtime.wait(long) or
    System.wait(long). Can anyone offer any >suggestions?Runtime.wait and System.wait should both not compile, giving an error that you are trying to call a non-static method from a static context (or something similar).

  • About threads question

    If only one thread write a basic type variable(like int,float),the other threads only read this variable,need use synchronize.
    thanks.

    If you're asking if you need to sync on a primitive type when that type is both read and written to (even by only one thread), the answer is it depends on the size of the type.
    If the type is 32-bit (4 bytes) or less (byte, short,int,float), the JVM spec garanties that the operation is atomic. (no need to sync)
    For 64-bit (8 bytes) data or more (double, long), the spec recommend that the JVM implementation treat the operation as atomic, but it is not required.
    If you need to sync, and you have only one thread writing to the data, and many threads reading it, consider using read-write locks, for efficiency. See Doug Lea's util.concurrent package .
    Try to make an effort in formulating your questions, that would help us help you...

  • Simple thread questions

    Hi
    I'm implementing a simple app with 2 threads:
    - Thread A creates thread B and then listens on a socket, waiting for a shutdown command.
    - Thread B executes some app specific processing until thread A notifies it to quit.
    My questions are:
    - How can thread A notify thread B that it should exit?
    - If thread B needs to exit (because some fatal error ocurred while doing its specific processing, how can it inform thread A that it should also exit?
    Thanks in advance!

    Have thread B execute within a while loop using a boolean initially set to true that is set to false by thread A to trigger a shutdown. Make thread A a daemon thread so it shuts down when no other threads are active.

  • Swing Multi-Thread Question. Is this safe?

    I want to use a Thread to get data from db and put it into my TableModel.
    This doesn't update the GUI directly but causes a fireTableChangedEvent... to be called which will ultimately cause the GUI to be updated.
    Question: Can I therfore use a plain Thread for this or must I use a SwingWorker?

    And now understand that a plain Thread is totally
    unnaceptable (which answers my original question),
    could you clarify the code below would be an
    alternative solution to my problem or if there is some
    reason why I MUST NOT use this:
    final SwingWorker worker = new SwingWorker()
    List data = null;
    public Object construct()
    data = dataFetcher.getDate();
    return null;
    public void finished()
    myTableModel.add(data);
    myTableModel.fireTableDataChanged();
    worker.start();
    Written this way, SwingWorker is fine, will update the model in the AWT thread.
    However, be careful of one thing: the code after worker.start() is executed immediately, which means concurrently with DataFetcher.getDate() and maybe before (or after) myTableModel.add(data).
    Of course this applies to who is calling the code above and so on.
    In other words you must be 100% certain that no application code is executed after worker.start() nor here nor up in the stack frames.
    Foxtrot will block there, guaranteeing you a correct behavior and no nasty surprises. Big gain in reducing complexity and improve mantainability IMHO.
    Simon

  • Threads question?

    Well, i'm not really sure if it is a thread issue but nevertheless here it goes:
    p below is a label and refreshList() is a processor intensive method
    which scans a network for open 1433 ports (sql server default port)
    the problem is that the "Scanning" status never has a chance to display.
    the system goes right into the refreshList and it takes over until its done and then the "done" status is displayed. So the question is
    how do i make sure that the "Scanning" shows up before i go into the refreshList() ?
    p.setText("Scanning")
    manager.refreshList();
    p.setText("done");

    as i assume p is a label.
    did u have a look at the method setText() of label?
    i don't think it's an thread issue because the part of code that sets the new text is synchronized - it is atomic...
    public void setText(String text)
    boolean testvalid = false;
    synchronized (this)
    if (text != this.text && (this.text == null || !this.text.equals(text)))
    this.text = text;
    LabelPeer peer = (LabelPeer)this.peer;
    if (peer != null)
    peer.setText(text);
    testvalid = true;
    // This could change the preferred size of the Component.
    if (testvalid && valid)
    invalidate();
    }try to call update or directly paint.

  • Thread question

    How would i make a thread that just watched for pressedKey events. I'm new to programming and am trying to learn threads. So far from my understanding, threads do something until they're done, and don't sit there like event listeners.

    it seems to me as if everyone did understand your question perfectly well. there are event handlers that can do all you ask for: detect when a key is pressed, detect when it is released, detect when it is pressed (i.e. pressed and released).
    eg:
    private void jList1KeyPressed(java.awt.event.KeyEvent evt) {                                 
    String key = evt.getKeyText(evt.getKeyCode());
    //escape close
    if (key.equalsIgnoreCase("escape")){
    this.dispose();
    // home top of list
    if (key.equalsIgnoreCase("home")){
    jList1.setSelectedIndex(0);
    // enter
    if (key.equalsIgnoreCase("enter")){
    this.select();
    etc etc
    attach the listener to your component thus:
    jList1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
    jList1KeyPressed(evt);
    });

  • Conceptual Thread question

    Good evening...
    i understand what multi-tasking and threading is.
    but what i'm having trouble with is the idea of having two threads communicate.
    for example a thread that reads several files simultaneously, and another thread that "requests" the most recent entry that was read from all the files.
    because it's not the entire object that runs in a separate thread right? it's really only the run() method, correct?
    thanks.
    so the run() method would have to do the work of reading the files and sorting what it reads, then stick it into a buffer where some other method of the object could return it when requested. is that the right way of thinking?

    Yes, something along those lines.
    Just because a Thread is running it doesn't prevent you from accessing its methods. Obviously attempting to call certain methods will throw IllegalStateExceptions and the like.
    If you want to get two Threads to communicate then you could either get one to regularly ask the other one questions, eg "do you have any more data for me?", or you could get one Thread to wait on the other Thread, thus only waking up when new data has arrived.
    In either case I would put some data buffer between them rather than actually within one of them.
    For example:
    public class ProducerThread extends Thread
      protected DataBuffer buffer;
      public ProducerThread(String filename, DataBuffer buffer)
        super("ProducerThread");
        this.buffer = buffer;
      public void run()
        try
          // Read in your data
          Iterator i = ...;
          while(i.hasNext())
            buffer.bufferData(i.next());
          buffer.setFinished(true);
        catch(Exception e)
          // Your exception handling
        finally
          // Close all your resources
    public class DataBuffer
      protected LinkedList dataList;
      protected boolean finished;
      public DataBuffer()
        dataList = new LinkedList();
        finished = false;
      public synchronized void bufferData(Object data)
        dataList.add(data);
        notifyAll(); // let anyone that's waiting for data know that some has arrived
      public synchronized Object waitForData() throws InterruptedException, IllegalStateException
        if(finished)
          throw new IllegalStateException("Buffer is finished");
        // If we can't return anything at this moment then get this thread to wait until another
        // thread puts something into the buffer
        if(dataList.empty())
          wait();
          if(dataList.empty()) // Usually caused by setFinished being called
            throw new IllegalStateException("Buffer is finished");
        return dataList.removeFirst();
      public boolean isFinished()
        return finished;
      public synchronized void setFinished(boolean finished)
        this.finished = finished;
        notifyAll(); // If someone's waiting then we should let them know that nothing's gonna happen
    public class ConsumerThread extends Thread
      protected DataBuffer buffer;
      public ConsumerThread(DataBuffer buffer)
        super("ConsumerThread");
        this.buffer = buffer;
      public void run()
        Object data;
        while(!buffer.isFinished())
          try
            data = buffer.waitForData();
          catch(Exception e)
            // Your exception handling code!
    }The code snippet uses synchronisation quite a bit to manage concurrent access to sensitive state.
    Just ask again if this doesn't make sense.
    Hope this helps.

  • Inner thread question

    class A {
    getName(){}
    setName(){}
    class B extends A{
    private class innerClass extends Thread{
    run(){
    getName()
    setName()
    The problem is that calling getName from inner class will use the getName from Thread beacuse that is it's super. How do I specify the getName from class A? The setName is OK because Thread does not have a setName

    The only way you could do this remove the extends A and call explicitly by creating an instance of A
    run(){
    A a = new A();
    a.getName()
    a.setName()
    Doug_99 wrote:
    class A {
    getName(){}
    setName(){}
    class B extends A{
    private class innerClass extends Thread{
    run(){
    getName()
    setName()
    The problem is that calling getName from inner class will use the getName from Thread beacuse that is it's super. How do I specify the getName from class A? The setName is OK because Thread does not have a setName

  • Number of Threads Question

    Hi,
    I'm working on a pretty big program and i need a lot of threads to make it run well (it's an audio player and, of course, i don't need people to wait when, for example, they save a playlist). So, i put some of these tasks on different threads, plus others that i didn't need for making the program run faster, but they are there just to make the program run. Now i have at least 4 threads running at the same time and, in some cases, there are even 6 or 7. Is it too much? It's my first big program (it's just for fun but i still want it to run well) and i didn't need so many threads before. What's the maximum number of threads you'd recommend me to have?
    Thanks.

    Anakin1989 wrote:
    Hi,
    I'm working on a pretty big program and i need a lot of threads to make it run well (it's an audio player and, of course, i don't need people to wait when, for example, they save a playlist). So, i put some of these tasks on different threads, plus others that i didn't need for making the program run faster, but they are there just to make the program run. Now i have at least 4 threads running at the same time and, in some cases, there are even 6 or 7. Is it too much? It's my first big program (it's just for fun but i still want it to run well) and i didn't need so many threads before. What's the maximum number of threads you'd recommend me to have?
    Thanks.Are you experiencing any problems with the number of Threads you have? If not, stop worrying. On the other hand, are you sure you need all of them? There are alternatives to Threading, such as SwingWorker and Timer that might be able to help you out.
    One thing you better make sure of is that you're not doing any Swing work off of the EDT, or doing things like sleeping or time-consuming work on the EDT.

  • Another thread question...

    i am new to working with threads so i really appreciate the help,
    anyways, i have a class where i want to launch a method as a thread. This
    method takes 2 arguments, both Strings.
    I can't come up with a good way to make sure that my method gets the right
    parameters for each launch before they are overwritten by the next
    incarnation of the primary thread.
         public synchronized void moveSingleFileThreaded(File FileBeingMoved, File FileWeAreMovingTo){
              currentMoveFromFile = FileBeingMoved;
              currentMoveToFile   = FileWeAreMovingTo;
              moverThread = new Thread(this,"Mover" + threadsCurrentlyRunning);
              moverThread.start();in the above code, i need to pass the 2 arguments into the method that will
    be threaded. However, that method is called in run(), and since run takes no
    arguments there is no way for me to pass them directly. In the above code i
    assign the parameters to class data members. However, i am afraid that I
    run
    the risk of these data members being overwritten before I call this function
    again. Am I too worried?
    thanks

    OK, that makes sense, and that was my first instinct
    of what to do. However,
    consider the following code:
    public class A implements Runnable{
    String INFO = null;
    private Thread myThread = null;
    public void A(String info){
    INFO = info;
    myThread = new Thread(this,"thread");
    myThread.start();
    }//end construct
    public void run(){
    String infoHolder = INFO;  //how can I make SURE
    SURE SURE that infoHolder always gets the right
    info?
    //do something with infoHolder....
    }//end class defI know that infoHolder is assigned the value of INFO
    in the first line of the
    thread, but can I be 100 percent sure this will
    execute as expected everytime?
    What happens if, for some crazy reason, the thread
    gets bumped from
    execution on the first line of the run() method, and
    when it resumes the
    constructor of this class has been called again, with
    different info?
    INFO and myThread are not static--each instance of "A" will have its own INFO value and its own myThread value. Calling the constructor creates a new instance of "A", so the original instance (that was suspended in your example) is not affected.
    Then I
    would have an erroneous thread once the original
    thread is put back into
    action.
    The tricky part for me is the fact that I need some
    of these threads to sleep
    before execution (because I will be copying over a
    network and don't want
    to overload resources).
    Any ideas? thanksAlso, initializing INFO and myThread to null is redundant--the JVM will do that automatically.

  • Basic threading question

    I've tried to understand threading from ten different tutorials, but it makes my head spin because all the tutorials include so much extra stuff that I don't know what's important.
    I've got a piece of code here with a gui, which contains a progress bar. I'd like the progress bar to update in a timely fashion, but not take up much of the main thread's recources.
    I've cut the code down to it's barest minimum. I'd really appreciate it if someone could tell me how to edit this code so that it implements threading. Thanks so very much.
    public class MeGA {
         private static Interface gui;
         private static EvolutionEngine engine;
         public static void main(String[] args) {
              engine = new EvolutionEngine();
              gui = new Interface(engine);
              engine.setGUI(gui);
    public class Interface {
         // A bunch of methods that set up the gui
         // And then my progress bar method
         public void updateProgressBar(int value){
              bar.setValue(value);
    public class EvolutionEngine {
         public void start() {
              For (int i=0; i<x; i++)
                   // Do a bunch of stuff
                   // then update progress bar
                   gui.updateProgressBar(i);
    }

    Thanks for the reply.
    The run() method works great now, and threads well with the progress bar.
    However, I can't seem to start it up again after the run() method has completed (i.e. pressing "run" on my gui, which calls engine.start() does nothing the second time around).
    The method run() has definately quit, and, as an experiment, I threw in a stop() command for good measure. Nothing.
    When I switch the threaded method for my original method, everything works fine (except it doesn't thread), so it's obviously something to do with the thread.
    Any suggestions as to why I don't seem to be able to call start() twice, when the first one should certainly have quit?
    Thanks!

Maybe you are looking for

  • Calendar event notes entered in IOS do not sync to exchange

    I have a user who just upgraded to an iphone 6.  When he creates a calendar entry in Outlook, (using exchange with ActiveSync) the entry shows on his iphone.  If he creates an entry on his iphone and fills in the Title, Location, and the Notes within

  • National date format

    How can I set national date format for entire Portal? I want to see all dates in 'dd.mm.yyyy' format instead of 'dd-MON-yyyy' - reports, forms, customization forms etc.

  • ALV - scope of list

    Hi Experts, I am modifying ME5j Transaction : Program : RM06BKPS I just copied the standard program into Zprogram. I haven't made any changes just copied to Zprogram. when i am executing Zprogram i gave Prject definition :XXXXXXXX and Scope of list =

  • Extracting images from pdf

    I am trying to extract images from pdfs using pdfimages, but i am unable to retrieve all the images. By opening the pdfs using Acrobat Reader 9.0, I am able to select, those images retrieved by pdfimages, using the select tool but for other figures/i

  • SSD users problems post Mountain Lion upgrade?

    HI folks.  I've had nothing but major problems with installing and booting since I upgraded my Mac to Mountain Lion.  I had no problems with Lion.  I do have an SSD installed and I'm wondering if that has something to do with it.  Anyone?  Thanks.