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

Similar Messages

  • 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

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

  • Inner classes question

    Hi guys,
    I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
    Is it how it's done or am i doing something wrong?
    public class A
        // Some code here
        public class B
             //Some code here
    }Trying to create an instance:
    A a = new A();
    A.B b = a.new B();

    What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
    >
    There are two ways to create "inner" class object,
    1)The way you have written the codeTrue.
    2)
        public class A
    {    // Some code here    
    public void createInner()
    classB b=new ClassB();
    public classB   
    //Some code here   
    That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway?

  • 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 Margin Question

    Hi everyone,
    I am designing an art catalog on 240 pages, size 200x280 mm, which will be perfectly bound.
    I wanted to have the outer margin larger than the other margins, however, I am not sure about the inner margin size - I originally set it at 15 mm, but now I am thinking it should be larger?
    Also, should I use inner margin bleed, as I have 2-page images on some of the pages?
    Thanks for your help.

    Is there a special reason for making your book just slightly smaller than A4 - your size doesn't seem to be one thing or the other.
    Margins are rather subjective. I suggest you go into a bookshop and look at books that are around your selected size and with the kind of design and content you want  and see which margins seems to work best.
    You wouldn't have inside bleed on books that are printed in sections.
    If your book is to be perfect bound, you will also need to produce cover artwork. This will be printed separately on heavier stock than the text and maybe laminated. The flat size of the cover artwork should be twice the size of the text trimmed page size plus and allowance for the spine.
    Design your book in double page spreads and supply the printer with single page PDFs with printers marks. Discuss with your printer all technical matters before proceeding.
    Derek

Maybe you are looking for

  • ICal events disappear only in Day and Week views

    Using iCal 3.0.2, I have suddenly acquired a new behavior. Several "subscribed" calendars appear fine in Month view, but their events do not appear in Day or Week view. I have deleted Caches > com.Apple.iCal and I have deleted Libraries > Calendars >

  • How do I create a path based on the arc of a crescent?

    I've created a crecsent by using the pathfinder and two circles. I also used the blend tool to create a line of evenly spaced, much smaller cirles. I want to create a path to use as a spline to align the series of small spheres evenly along a path th

  • My macbook pro with 16GB ram runs out of application cache very often, and only application running is FIREFOX MOZILLA. How to fix this?

    This happens 2 or 3 times a day - every couple of hours. Then, I need to restart the laptop and clean out files (I use ccleaner). Is there a way to fix this ( system running out of application cache). Thought 16 GB ram would be big enough. Thanks for

  • Weird verb behavior...

    I just discovered today on one track of a project that the reverb tail was cut before it is supposed. It really stop instantly after 1, 2 or 3 seconds randomly when it's supposed to last 17 seconds in a smooth fade. Looking for the source, I tried to

  • BAPI for Partial Confirmation CO11N

    Dear Gurus, REG : BAPI How to get the actual activites for partial confirmation of qty we have tried some bapis like for getting activites we have used bapi_prodordconf_get_tt_prop but in this bapi it is calculating total qty i.e, order qty not for t