What exactly is the main thread?

please consider this code:
public class Foo {
    public static void main(String[] args) {
          ((Foo) Thread.currentThread()).bar(); // <--- error. see stack trace below.
    public void bar() {
        System.out.println("--bar()--");
}stack trace: Exception in thread "main" java.lang.ClassCastException: java.lang.Thread cannot be cast to testingarea.Foo
So what does this say about the main entry thread? is it an instance of "Foo"? or an instance of java.lang.Thread? If an instance of "Foo" why can't I invoke an instance method on the return value of "Thread.currentThread()"? If the main thread is an instance of java.lang.Thread, then where is the:
"public void run();" method?
While I can't think of any practical usage of this knowledge yet, but I'd still like to know. Thanks.
Edited by: outekko on Mar 17, 2010 6:38 PM

joshg_75 wrote:
You should always refer to the javadoc for infomation of a method and its usage. In this case, refer to the javadoc of the Thread class.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html
I suggest you also read up on usage of threads.Can you please share a little of your expertise in threads?
Remember this is the "New To Java" forum, and I am just a beginner as you discovered. Any help from experts would be embraced. Before you became a thread expert, you must have started somewhere. I don't need immediate assistance, but whenever you get the time, why not cut/paste this into your IDE and take a look.
public class Main {
  static ObjectOutputStream oos;
  static ObjectInputStream ois;
  public static void main(String[] args) {
    try {
      PipedInputStream pin = new PipedInputStream();
      PipedOutputStream pout = new PipedOutputStream(pin);
      oos = new ObjectOutputStream(pout);
      ois = new ObjectInputStream(pin);
      new OutThread().start();
      for(;;) {
        Thread t = (Thread) ois.readObject();
        t.start();
    } catch (Exception e) { e.printStackTrace(); }
      public static class OutThread extends Thread implements Serializable {
        public void run() {
          System.out.println("OutThread::run--> id# " + this.getId());
          try { Thread.sleep(1030); } catch (InterruptedException e) {  }
          try {
            oos.writeObject(this);
            hangAround();
          } catch (Exception e) { e.printStackTrace(); }
        public void hangAround() {
          for (;;) {
            System.out.println("_____waiting around... id# " + this.getId());
            try { Thread.sleep(5030); } catch (InterruptedException e) {  }
}Not only do I appear to serialize instances of threads, the threads are actually running . So, does a live thread have private, non-transient, "state" that needs to be persisted? If so, why does serialization work? If not, why not write in the API that java.lang.Thread implements Serializable ? Whatever understanding (if any) I had of threads has melted to nothing. I am struggling with your field of expertise; please help me get back on track. Any assistance embraced.
ps. don't offer friendly criticism by scolding my design of serialized threads. My only goal is to see if I can do it (and learn something along the way).

Similar Messages

  • What exactly is the diff between main window and variable window

    what exactly is the diff between main window and variable window in SAP script?

    hi,
    MAIN WINDOW :- In a main window you display text and data, which can cover several pages (flow text). As soon as a main window is completely filled with text and data, the system continues displaying the text in the main window of the next page. It automatically triggers the page break.
    You can define only have one window in a form as main window.
    The main window must have the same width on each page, but can differ in height.
    A page without main window must not call itself as next page, since this would trigger an endless loop. In such a case, the system automatically terminates after three pages.
    VARIABLE WINDOW :- The contents of variable windows is processed again for each page, on which the window appears. The system outputs only as much text as fits into the window. Text exceeding the window size is truncated; the system does not trigger a page break. Unlike constant windows, the page windows declared as variable windows may have different sizes on different form pages.
    As far as the processing of the window contents is concerned, the system currently treats constant and variable windows alike. The only difference is that constant windows have the same size throughout the form.
    hope this will be useful.
    If useful then reward points.
    with regards,
    Syed

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Waiting the main thread till all child thread has completed

    I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
    1. Retrieve values from DB and populate a blocking queue in main thread.
    2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
    3. Invoking the following block of code from the main thread,
    while(!iBlockingQueue.isEmpty()) {
        AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
        iThreadPool.execute(lProcessor);
    }DefaultProcessor is a class that extends Thread.
    4. Invoking the following block of code from the main thread,
    iThreadPool.shutdown();
    try {
         iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
         } catch (InterruptedException interruptedException) {
              iLogger.debug("Error in await termination...", interruptedException);
    Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
    Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
    I will appreciate any inputs on this.
    Thanks.

    looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
    the threadpool's internal queue is all that is needed
    if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
    by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
    DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
    to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
    class DefaultProcessor implements Runnable {
      private BlockingQueue myQ;
      private boolean myStopFlag;
      DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
      public void run() {
        BusinessObject bo = null;
        while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
          // business code here
      public void stop() { myStopFlag = true; }
    } Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

  • What exactly are the updates good for on an ipod

    I ask because mine is windows format, and im having trouble transferring all the metadata off my ipod with senuti to a back up so that i can reformat the ipod to mac and then sync in my senuti backed up library. I was wondering if anyone knows what exactly are the updates that you get. my ipod is 1.2 5thgen.
    If i were to have the latest update would i be able to see album cover art view when the ipod is plugged into itunes? I noticed that i can see that view in library mode but not in ipod mode. (my pod isnt synced)...
    so what are these updates good for?

    hey thanks for your reply.
    I do have it set to manual and i can see the art on the ipod by itself, but even with manual transfer itunes wont let me view the artwork modes unless i am playing off my computers library (which doesn't have the songs on my ipod on it). I called apple earlier today and some tech support guy claimed that itunes does not support this feature. Is this correct? can anyone out there see artwork modes on an unsynced ipod through itunes?

  • How to make the main() thread wait?

    I would like to know how to make the main() thread wait for another thread?If I use wait() method in main() method it says "non-static method wait() cannot be referenced from a static context",since main()
    is static.

    Here is an example how you may wait for a Thread in the main -
    but be careful, this is no real OO:
    public class WaitMain {
    // this is the thread class - you may also create
    // a runnable - I use a inner class to
    // keep my example simple
         public static class ThreadWait extends Thread{
              public void doSomething(){
                   synchronized(syncObject){
                        System.out.println("Do Something");
                        syncObject.notify();
              public void run(){
                   // sleep 10 seconds - this is
                   // a placeholder to do something in the thread
                   try{
                        sleep(10000);
                        doSomething();
                        sleep(10000);
                   catch(InterruptedException exc){
    // this is the object we wait for -
    // it is just a synchronizer, nothing else
         private static Object syncObject = new Object();
         public static void main(String[] args) {
              System.out.println("This will start a thread and wait for \"doSomething\"");
              ThreadWait t= new ThreadWait();
              t.start();
              synchronized(syncObject){
                   try{
    // this will wait for the notify
                        syncObject.wait();
                        System.out.println("The doSomething is now over!");
                   catch(InterruptedException exc){
              // do your stuff

  • What exactly does the Radio Beacon Indicate

    I have seen cases where the Radio Beacon is black and when it is gray. When it's black you may or may not be able to go through the wireless router to the modem and then to the internet. When it is gray, you cannot really do anything except be in a local mode. However there are instances when the Radio Beacon is black, rather than gray, and you still cannot access the internet. So, what exactly does the activated Radio Beacon Indicate, i.e., that the wireless network is working and the modem is down, or something else entirely ?

    Assuming you're referring to the Airport icon in the menu bar, 'clear/empty' means Airport is turned off, gray bars means Airport is on but not connected to a network, and black bars means Airport is on and connected to a network. Other possible icon states are solid gray with a little computer inset, meaning you're connected to a computer-to-computer created on the Mac, and gray bars with an exclamation point (10.6 only), meaning connected to a network but not authenticated (e.g. wrong password for an 801.2X corporate/university network).
    To your question, it's perfectly possible to be successfully connected to a network (black icon) and unable to access the internet. Situations like that would include the network requiring a proxy server, for which you haven't set up the details on in Network Preferences, or you're connected to an open network that requires you to enter information or agree to terms (e.g. a hotel network, where you need to put in your room number and agree to the charges before you can connect to the internet).

  • What exactly does the global switch command line do ?

    Hello All
    Just foraging in the dark world of APP-V. I have a question which I cannot find answer for through google.
    There are powershell commands to publish an APP-V application globally. What exactly does the global switch do ?
    I understand it makes the application available to everyone on the machine for anyone who logs onto that machine.
    However in the absence of this global switch the application is still available to all users who logon to that particular machine. So what exactly is the reason for using the global switch ?
    Thanks

    Correct, the global switch makes the application accessable for all users logging on to that system.
    This feature is required for some packages, like Office. But it is ofter used for applications used by everyone, like Adobe Reader.
    However in the absence of this global switch the application is still available to all users who logon to that particular machine. So what exactly is the reason for using the global switch ?
    A package can be added to the system but until it is published a user cannot start it. They won't see any shortcuts in their startmenu/desktop/etc.
    So after you added the package to the system, it must be published to a user or globally (every user) to start it.

  • What "exactly" does the Brightness setting in Print do?

    What "exactly" does the Brightness setting in the Print module do?
    I know it's a controversial button, especially now that there are proofing options available. Also, since you're using it "blind" it's impossible to know how much or what it's really doing.
    Does anyone know if it's e.g.. the same as going to quick develop and going up on "exposure", or "brightness", or "shadows"... How exactly is it brightening the image, and is +100 a full stop or how is it calibrated?
    Thanks,
    Alan.

    Ooops,
    Obviously there is NO brightness control in LR...is the print adjustment similar to an exposure adjustment or more like moving the "shadows" and "whites" adjustments (which if I understand corrrectly, moves tones above or below mid tones, but not highlights or blacks)?

  • What exactly are the cron scripts doing?

    Hi,
    Hope the subject says it all: I have searched but not found a detailed explanation as what the cron scripts (daily, weekly, monthly) actually do, and if the utilities (Onyx, Cocktail, Xupport, etc) are doing exactly the same.
    Can someone point to a site or explain?
    TIA
    Dan

    Hi Dan,
    (in addition to Barry's reply)
    Yes,
    1) running the Daily, the Weekly and the Monthly tasks manually with an utility, or
    2) running them yourself with the
    sudo periodic daily
    sudo periodic weekly
    sudo periodic monthly
    Terminal commands
    (or this one: sudo periodic daily weekly monthly), or
    3) leaving your computer running 24/7/365 so that they run automatically,
    all three ways do exactly the same thing.
    --> To see what they do exactly, the best way is to open Console, and in the /var/log section, look for "daily.out", "weekly.out" and "monthly.out".
    What exactly are the "cron scripts" doing?
    (Periodic tasks)
    In Console, you'll find a lot of different files that grow with more and more information every minute, even every second for some of them.
    The three Periodic tasks regularly rearrange them and compresses them so that they don't take too much disk space.
    They also rebuild some system database so that the data never gets unusable by the system.
    HTH
    Axl
    201

  • I wish I could remember what exactly happenned the last time I upgraded iphoto years ago, but something

    I wish I could remember what exactly happenned the last time I upgraded iPhoto years ago. Did my address book go kaflooey? But whateverit was, it discouraged me from any updating eversince.  Believe it or not, I have been limping along with Iphoto 6.0.6 and basically faring fine, given my needs.  But I would now like to be able to order prints from my photo library -- and you can't do that any longer with 6.  So my question is:  what are the things that
    can go wrong with the later systems?  And is there any way around having that happen?

    Make a back up.
    Make a second.
    Upgrade. Get on with your life.
    Regards
    TD

  • What exactly does the Work Offline option do in a shared review hosted on an internal server?

    Hi,
    What exactly does the Work Offline option do in a shared review hosted on an internal server?
    I *think* it simply disconnects you from the review server. I'm not sure why one would want to do this.
    I'm trying to recommend an offline workflow for reviewers who may not be able to access a shared review hosted on our internal server (for example, while traveling). These reviewers would like to be able to comment on an offline version of the review PDF and then publish their comments when they can again connect to the Internet/internal server.
    It doesn't seem like "Work Offline"  is the right fit for this scenario. Instead, should reviewers save a local copy to their hard drive, comment on it, and then, when reconnected to the Internet, open the local copy, click Reconnect to Server, and then click Publish Comments?

    Thanks, Dave. So for my hypothetical traveling reviewer, it would be reasonable to suggest the following steps for an offline workflow?
    1. Connect to the shared review.
    2. Choose Work Offline from the Server Status menu.
    3. Close and save the review PDF locally.
    4. Comment while traveling.
    5. When back in the office, open the local copy of the review PDF.
    6. Click Reconnect to Server.
    7. Click Publish Comments.

  • What exactly are the free levels of Adobe services?

    What exactly are the free levels of Adobe services?

    Cloud Plans http://www.adobe.com/products/creativecloud/buying-guide-at-a-glance.html may help

  • What exactly is the auto letterbox and pillarbox option?

    Can't find any reference to that preference in the help file. Can someone define exactly what that option does?
    I'm guessing its affecting a project I'm working on. I just imported about 40 minutes of footage from a mini-DV camcorder. The person who shot it must have turned on one of those fake widescreen effects in the camcorder because the footage has black bars on top and bottom. Anyway, after the tape was finished importing iMovie put up a status box stating: "Letterboxing - Please wait this may take a while." Well its been about 2 hours now and its still not finished. I'm not even sure what the heck its doing.
    Thanks,
    Chris

    What issue?"
    That is what I am asking...Like I said, I am able to open CS5 on my new retina mbp and edit image files with no issue..the only thing that I notice that seems off is the text of the UI seems "fuzzy"....
    So, what I am asking is what exactly is the problem supposed to be that I should be seeing?

  • What exactly is the issue with CS5 and the retina display?

    Just picked up a late 2013 MBP with retina display and have PS CS5 running on it.
    What is the exact issue that I should be having when it comes to running CS5 on these machines ?  Is it just that the UI looks fuzzy?  Other than that it seems to run fine and my photos look fine also.

    What issue?"
    That is what I am asking...Like I said, I am able to open CS5 on my new retina mbp and edit image files with no issue..the only thing that I notice that seems off is the text of the UI seems "fuzzy"....
    So, what I am asking is what exactly is the problem supposed to be that I should be seeing?

Maybe you are looking for

  • Outlook mail account setup issues

    I just bought a surface pro3 and installed office 365. When I go to open Outlook and create an account it gives me the following error. "The connection to Microsoft Exchange is currently unavailable. Outlook must be connected or online to complete th

  • Photoshop CS6 Extended Upgrade

    Where can I get Adobe CS6 Extended upgrade (from CS5 Extended) for windows on a disk and NOT a download and what is the cost? I don't want an eduction copy.

  • Elements 12 license not valid

    I purchased Elements 12 for Mac via the Adobe site from a Mac, however the license that was sent to me says Windows, and doesn't work on my download. I've rechecked the purchase process and it shows me as purchasing the Mac version, so I don't know w

  • Can I Easily Time Stamp in Numbers?

    I want to create a Numbers form that automatically time stamps when I make the entry.  Is this possible to do on an iPad?

  • I cannot fix this problem no matter what I try, please help!!

    My iPod Touch is stuck in the past. No matter what I do or change, the date always reverts back to December 31, 1969. I wouldn't mind hanging out on New Years Eve in 1969 with all the hippies listening to Jimi Hendrix and Jim Morrison but let's face