Need blocking method without blocking main thread

I have this problem:
public void blockingMethod() {
  frame.setVisible(true);
  // wait for the user to click on a button on the frame
  return;
}I want to make a method blocking until the user press a button on the frame. However, I can't make the current thread sleep or wait and then notify it when the button is pressed, because it is the main thread that calls this method. And the main thread is responsible for listening to events and repaint the frame.
I could solve my problem by using a modal Dialog and let the user enter some data there and then exit the Dialog. Dialog.show() would block until the user exits it again. But I would rather use my frame, so I took a look at the code for Dialog.show() method, and it does something like this:
EventDispatchThread dispatchThread =(EventDispatchThread)Thread.currentThread();
* pump events, filter out input events for
* component not belong to our modal dialog.
* we already disabled other components in native code
* but because the event is posted from a different
* thread so it's possible that there are some events
* for other component already posted in the queue
* before we decide do modal show. 
dispatchThread.pumpEventsForHierarchy(new Conditional() {
  public boolean evaluate() {
    return keepBlocking && windowClosingException == null;
}, this);But EventDispatchThread is package protected, so I can't do this.
Any suggestions? I think there are circumstances where you would like a method block, but where it is the main thread that calls the method (out of my control), and you would not like the main thread block unless you could make sure the gui would still repaint and events would run.

Ah, nm. The main thread is not the same as the event thread.
Whew! :)
The first who reply will get the dukes.

Similar Messages

  • Main thread is busy, cannot receive callbacks

    Hi,
    I'm using the measurement studio activeX control to program my application. (NI-DAQ 6071E) My main thread is always busy because there's a lot of calculating and graphing. I'm using the CWAI control to do continuous caputuring. When the program is very busy for displaying the data, it will miss the callbacks or give error. My question is, is it possible to create measurement studio controls in a worker thread, so that the callbacks will be recieved in the worker thread? If not possible, is there any work around? I tried to use windows messageas to get around. The program is it still need to go through the main thread. The bottom line is callbacks cannot have anything to do with main thread. Thank you.
    Dona
    ld Yeung
    Software Engineer
    Tensor Biosciences

    In general, free threading in Visual Basic 6 is not supported. If you can't take no for an answer, though, check out Chapter 13 of Advanced Visual Basic 6 : Power Techniques for Everyday Programs.
    Another option would be to upgrade to VB.NET. For more information, see HOW TO: Create Threads in Visual Basic .NET and INFO: Roadmap for Threading in Visual Basic .NET.
    - Elton

  • Blocking the applet and main threads ?

    The thread that runs the Applet callback methods like init() and start() is a thread named �applet-your.package.your.classname.class�.
    If I am doing a blocking method call, i.e. a method call that does not return immediately like doing I/O read on a socket connection, is it ok to do it on the thread mentioned above ? In other words, is it ok to hang/suspend/block the applet thread ?
    What about blocking the �main� thread that calls
    public static void main(String args[]) {�}
    Thanks.

    eminformatics, thanks for the reply.

  • How to blocks the main thread

    Hello,
    I have a multi-threaded application but the main thread doesnt blocks the application so the application quits just after started. Im using this code to block the main thread:
    /*BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    for(;;) {
    try {
    r.readLine();
    catch (IOException e) {
    I tryed to just use for(;;){} but it causes 100% of CPU using. This code above its very dangerous because sometimes System.in blocks the entire application (all threads)
    Thanks a lot

    This application its a socket server, Im doing:
    main {
    Thread1 - createServer();
    Thread2 - createLogging();
    waitForServerShutDown();
    the createServer method must be placed in a thread, its must not blocks the application because createLogging(); must be executed just after the server was created and createLogging(); doesnt blocks the application then... I must block the main{} to keeps application running

  • SSL connections blocking worker threads on DS 5.2 patch 4

    Hi,
    Is it normal for an idle SSL connection to consume a worker thread within the directory server?
    We have recently enabled SSL on a number of our directory servers (5.2 patch 4) and have run into problems with the server hanging. We have a number of application servers, each opening a pool of connections to the servers via JNDI. It seems that once 30 SSL connections have been established to a give LDAP server, the server will hang. By hang I mean the server is accepting TCP connections, but not responding to LDAP requests.
    The server can deal with a lot more than 30 non-ssl connections. I'm guessing that SSL connections need to maintain state, which is what is tying up the worker threads.
    Is this normal, and is it docuemented anywhere? Currently I'm looking at terminating the SSL connections on a load balancer in front of the LDAP servers, or perhaps on an LDAP proxy. Any other suggestions as to how this is typically dealt with?
    thanks,
    R

    Thank you Gautam.
    On further testing yesterday, we discovered that the problem is just as you have described. Our application servers are opening an initial pool of five connections, but typically only using one of those connections. The one connection the server uses to make an LDAP request behaves 'normally', not tying up a thread on the LDAP server. The other four sit there blocking a thread each, until eventually we hit the nsslapd-threadnumber.
    Based on that discovery, we're having the application changed so that its initial LDAP connection pool size is one, which appears to address the problem. That way connections are only established and added to the pool as they are required, resulting in well behaved connections to the LDAP server.
    Thanks for the quick reply... The Sunsolve note is helpful, as is the info about the nsslapd-ioblocktimeout parameter.
    kind regards,
    R

  • I need block a particular site, just like in IE when i goto Privacy option I can specify and site & say Block - where can i find thi s in firefox?

    I need block a particular site, just like in IE when i goto Privacy option I can specify and site & say Block - where can i find thi s in firefox?
    I've been getting some junk websites while I am working. I need to block them completely.
    Please advise. Thanks,

    There is no equivalent in Firefox. You can use the [https://addons.mozilla.org/en-US/firefox/addon/3145/ BlockSite] extension to add a similar feature.
    If the junk sites are coming up whilst you are browsing, this may be caused by malware. You should consider scanning your computer with some malware programs. It is best to run several as each will pick up things that the others miss. Some scanners you can try are:
    * [http://www.malwarebytes.org/mbam.php Malwarebytes]
    * [http://www.superantispyware.com/ SUPERAntiSpyware]
    * [http://www.lavasoft.com/products/ad_aware_free.php Ad-Aware]
    * [http://www.microsoft.com/windows/products/winfamily/defender/default.mspx Windows Defender]
    * [http://www.safer-networking.org/en/home/index.html Spybot S&D]

  • I need block diagrams for audio processing effects such as echo,flanger,vibrato,chorus for implementing in labview?

    i need block diagrams for audio processing effects such as echo,flanger,vibrato,chorus  for implementing in labview? pls i need it very quickly........

    Hi komalamani,
    i need it very quickly...
    So you better start coding soon!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Pass messages between main thread and FX application thread

    I'm launching an FX Application thread from a Main thread using Application.launch [outlined here: {thread:id=2530636}]
    I'm trying to have the Aplication thread return information to the Main thread, but Application.launch returns void. Is there an easy way to communicate between the Main thread and the Application thread?
    So far I have googled and found:
    - MOM (Message Orientated Middleware)
    - Sockets
    Any thoughts/ideas/examples are appreciated - especially examples ;) - right now I am looking at using Sockets to show/hide the application and for passing data.
    What is the preferred method? Are there others which I have not found (gasp) via Google?
    Dave.
    Edited by: cr0ck3t on 30-Apr-2013 21:04
    Edited by: cr0ck3t on 30-Apr-2013 21:05

    Is there an easy way to get a reference to these objects from both the Main thread and the FX Application thread - called via Application.launch() from the Main thread? Or do I have to use Sockets or MOM?Not much to do with concurrent programming is what I would call easy. It seems easy - but it's not.
    You can kind of do what you are describing using Java concurrency constructs without using sockets or some Message Oriented Middleware (MOM) package.
    With the Java concurrency stuff you are really implementing your own form or lightweight MOM.
    If you have quite a complex application with lots of messages going back and forth then some kind of MOM package such as camel or ActiveMQ (http://camel.apache.org) is useful.
    You can find a sample of various thread interactions with JavaFX here:
    https://gist.github.com/jewelsea/5500981 "Simulation of dragons eating dwarves using multiple threads"
    Linked code is just demo-ware to try out different concurrency facilities and not necessarily a recommended strategy.
    If your curious, you could take a look at it and try to work out what it is, what it does and how it does it.
    The main pattern followed is that from a blocking queue:
    http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
    Note that once you call launch from the main thread, no subsequent statements in the main method will be run until the JavaFX application shuts down. So you can't really launch from the main thread and communicate with a JavaFX app from the main thread. Instead you need to spawn another thread (or set of threads) for communication with the JavaFX app.
    But really, in most cases, the best solution with concurrency is not to deal with it at all (or at least as little as possible). Write everything in JavaFX, use the JavaFX animation framework for timing related stuff and use the JavaFX concurrency utilities for times when you really need multiple thread interaction.
    http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
    To get further help, you might be better off describing exactly (i.e. really specific) what you are trying to do in a new question, perhaps with a sample solution in an sscce http://sscce.org

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

  • 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);

  • No UI Updating On Main Thread

    I have a few Cocoa UI elements with outlet connexions to an object instantiated within an NSView object, which is in turn put there by an NSViewController. These elements, a definite progress bar and a text label, are not updating: the progress bar is dead and empty despite having its value change constantly, the text label does not unhide through [textLabel setHidden:NO], the text label does not change its string.
    What I know:
    * There's no difference between binding values and setting them in code. Nothing changes either way.
    * I've checked outlet connections. They're all there.
    * I've tried [X displayIfNeeded], where X has been the UI objects themselves, the containing NSView, and the main window. No difference.
    * [progressBar setUsesThreadedAnimation:YES] makes no difference. Interestingly, if I look at progressBar mid-program, _threadedAnimation is still NO.
    * The object holding all these outlets and performing an import operation is in an NSOperationQueue owned by the NSViewController object. The UI update, meanwhile, occurs in the main thread via [self performSelectorOnMainThread:@selector(updateProgress:) withObject:(some number) waitUntilDone:NO]:
    - (void)updateProgress:(NSNumber *)someNumber
    if (someNumber == 1)
    [progressText setHidden:NO];
    [progress setUsesThreadedAnimation:YES];
    [progress setMaxValue:[max doubleValue]];
    NSInteger pctDone = someNumber / [max intValue] * 100;
    [progressText setStringValue:[NSString stringWithFormat:@"%d%% imported", pctDone]];
    [progress setDoubleValue:someNumber];
    [startView setNeedsDisplay:YES];
    I comment in-and-out some of the lines in updateProgress: depending on the experiment. According to the debugger, flow is clearly reaching this method, and it's clearly happening on the main thread. And yet, still no update. What else can I try?
    Thanks!

    Hi William -
    William Oram wrote:
    - (void)updateProgress:(NSNumber *)someNumber
    if (someNumber == 1) // <-- (1) comparing address of object with int
    [progressText setHidden:NO];
    [progress setUsesThreadedAnimation:YES];
    [progress setMaxValue:[max doubleValue]];
    NSInteger pctDone = someNumber / [max intValue] * 100; // <-- (2) dividing address by int
    [progressText setStringValue:[NSString stringWithFormat:@"%d%% imported", pctDone]];
    [progress setDoubleValue:someNumber]; // <-- (3) parameter is address instead of double
    [startView setNeedsDisplay:YES];
    It's hard to guess what's going on since the posted code doesn't appear to be the code you actually ran. As commented above, 'someNumber' is the address of a NSNumber type object so it can't be used where an int or a double is expected. It's generally best to paste code into the forum directly from your source files.
    Assuming 'someNumber' is a double in your actual code, I see two places at first glance that might account for what you reported:
    1) A double isn't often equal to an int, so the code block under line 1 might never run. If you're sure (rarely a useful concept in programming) 'someNumber' will be less than some value in the first of a series of calls to updateProgress, test with the less-than operator. Never use the equals operator to test a floating point value. That said, it would be much better to put that init code somewhere else (such as awakeFromNib). If 'max' varies, then put the init code in the same block that resets 'max'.
    2) The code doesn't set a minimum value for the progress bar. In my version of IB, the minimum for that object defaults to 20. Check and see if you reset that field in IB. Else if 'someNumber' never exceeds 20, you might never see a change in the bar.
    If neither of the above applies, the next place to look would be in your nib(s). It's always a good idea to make sure your IBOutlet ivars actually point where you expect.
    * I've checked outlet connections. They're all there.
    Even if the ivars aren't nil, they don't necessarily point to the view objects you're observing. I would recommend checking either the superview or window property (or both) of 'progressText' and 'progress'. I prefer logging these values with code placed immediately before the ivars are used.
    I made a testbed for you to factor out some of the complications and demonstrate the kind of logging I recommend:
    // MyViewController.h
    @interface MyViewController : NSViewController {
    IBOutlet NSTextField *progressText;
    IBOutlet NSProgressIndicator *progress;
    NSNumber *max;
    - (IBAction)someProgress:(id)sender;
    @end
    // MyViewController.m
    #import "MyViewController.h"
    @implementation MyViewController
    - (void)awakeFromNib {
    NSLog(@"awakeFromNib");
    NSLog(@"self.view=%@", self.view);
    NSLog(@"self.view.window=%@", self.view.window);
    NSLog(@"self.view.window.contentView=%@", self.view.window.contentView);
    NSLog(@"progressText=%@", progressText);
    NSLog(@"progressText.superview=%@", progressText.superview);
    NSLog(@"progress=%@", progress);
    NSLog(@"progress.superview=%@", progress.superview);
    max = [NSNumber numberWithInt:10];
    - (void)updateProgress:(NSNumber *)someNumber
    int someInt = [someNumber intValue];
    NSLog(@"someInt=%d", someInt);
    if (someInt == 1)
    [progressText setHidden:NO];
    [progress setUsesThreadedAnimation:YES];
    [progress setMinValue:0.0];
    [progress setMaxValue:[max doubleValue]];
    NSLog(@"progressText=%@", progressText);
    NSLog(@"progressText.superview=%@", progressText.superview);
    NSLog(@"progress=%@", progress);
    NSLog(@"progress.superview=%@", progress.superview);
    NSInteger pctDone = (double)someInt / [max intValue] * 100;
    if (pctDone <= 100)
    [progressText setStringValue:[NSString stringWithFormat:@"%d%% imported", pctDone]];
    [progress setDoubleValue:(double)someInt];
    - (IBAction)someProgress:(id)sender {
    static int isave = 0;
    NSLog(@"**someProgress**");
    NSNumber *number = [NSNumber numberWithInt:++isave];
    [self updateProgress:number];
    @end
    The progress bar and label are added directly to the content view of the main window. I.e. I didn't add startView, which I assume is the superview for the bar and label in your project. I like to keep testbeds as simple as possible to isolate the objects being tested. startView can be added after the basic testbed is running correctly.
    The progress bar is inited inside updateProgress to keep the code structure similar to your project, but as mentioned above, that code wants to be moved elsewhere to avoid the problematic init-required test.
    To build the testbed, just add a MyController class to the Cocoa App template, paste the example code into the files for that class, add a top-level object of type MyController to MainMenu.xib and connect its 'view' outlet to the content view of the window. Then drag NSProgressIndicator, NSTextField and NSButton objects onto the window. Connect the 'progressText' and 'progress' outlets of the controller, and connect the action of the button to 'someProgress' in the controller.
    Taking a few minutes to build a separate testbed might be well worth your time. Once the testbed is running, you can use it as a baseline for comparison with your project. The example testbed is working, tested code. So if you can't get it to run correctly, we can focus on your nib files. Similarly, if the working testbed fails when startView or some other feature of your project is added, we'll know where to look.
    - Ray

  • Exception in thread "Main Thread" java.lang.NoClassDefFoundError: weblogic/diagnostics/instrumentation/JoinPoint

    Hi,
    I have an application jar file which is run from a .sh file.
    The application uses ridc api to checkin a document on UCM.
    I have placed jars for supporting the application on the folder where we have kept the application jar
    also we have mentioned the supporting jar file names in the Manifest.mf file of the application jar.
    The necessary jar files which we have placed are:
    com.lnt.ucm.integrationutility.ucm.Client
    log4j-1.2.16.jar
    oracle.ucm.ridc-11.1.1.jar
    poi-2.5.1.jar
    commons-codec-1.2.jar
    commons-httpclient-3.1.jar
    commons-logging-1.0.4.jar
    mail.jar
    jxl-2.6.10.jar
    com.bea.core.antlr.runtime_2.7.7.jar
    com.oracle.toplink_1.0.0.0_11-1-1-5-0.jar
    jrf.jar
    org.eclipse.persistence_1.1.0.0_2-1.jar
    weblogic.jar
    wlfullclient.jar
    wseeclient.jar
    jaxws-rt-2.1.4.jar
    we are getting below exception when we run the jar from the .sh file.
    Exception in thread "Main Thread" java.lang.NoClassDefFoundError: weblogic/diagnostics/instrumentation/JoinPoint
    at weblogic.wsee.jaxws.spi.WLSProvider.<clinit>(WLSProvider.java:90)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at javax.xml.ws.spi.FactoryFinder.newInstance(FactoryFinder.java:31)
    at javax.xml.ws.spi.FactoryFinder.find(FactoryFinder.java:90)
    at javax.xml.ws.spi.Provider.provider(Provider.java:83)
    at javax.xml.ws.Service.<init>(Service.java:56)
    at com.abc.ucm.proxy.JDEUCMManagerService.<init>(JDEUCMManagerService.java:66)
    at com.abc.ucm.integrationutility.ucm.Client.executeUtilty(Client.java:50)
    at com.abc.ucm.integrationutility.ucm.Client.main(Client.java:540)
    I'm not able to find any jar for weblogic/diagnostics/instrumentation/JoinPoint can you please tell me which jar needs to be added.
    Regards,
    Tejaswini L

    914897 wrote:
    I encounter the similar error. Anyone knows how to fix it?By providing a configuration file which validates with the corresponding XSDs found in coherence.jar. Sorry, but can't point you to the specific issue without seeing the erroneous configuration file.
    Best regards,
    Robert

  • Main Thread is Foreground thread or Background thread ?

    The .NET Framework defines two types of threads: foreground and background.
    By default when we create a thread, it is a foreground thread, but we can change it to a background
    All processes have at least one thread of execution, which is usually called the main thread because it is the one that is executed when your program begins.
    Is this main thread is back ground or foreground thread.
    Regards
    krrishbiju

    The difference between a foreground thread/process is the priority and the parent/child ordering.  A main process/thread is the parent with higher priority while the background process/thread is the child with lower priority.  There is very little
    different between a process and a thread.  A class object is also a process.
    Processes run until a blocking method stops the execution (waits for an event before continuing) or when the operating system periodically performs a task switch to allow all processes a chance to run.  Processes with higher priority are allowed to
    run more often than processes with lower priority.
    jdweng

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

  • Main thread

    Is it possible to schedule a Runnable object on the main event thread from another thread in a NON_GUI app.
    Something kind of similar to the SwingUtilities.invokeLater() method but instead off running on the Event Dispatch thread run it on the Main thread.

    What is it that only works
    when executed on the "main thread"? All my calls to the COM API. If this is done on any
    other thread my calls do not work...I would shout a JIntegra then. This is very weird. COM does have some odd thread affinity stuff, but it's on the receiving end, not the calling end.
    Ah, so how do I pass a request to the main thread?
    This is what I need to do.As already mentioned by myself and others, there is no standard way to do this. A GUI toolkit gives you the ability to run "tasks" on the "event thread" (which isn't necessarily the same as the "main thread") but that doesn't help you.
    You'll need to build this functionality yourself using the tools and techniques available to you in Java such as synchronisation and the various concurrency classes.
    The problem is, the main thread is almost certainly "doing something". You can't just have it do something else. It's running your code, sequentially. You would have to make your main thread enter a loop where it waits for tasks delegated from other threads, executes them and hands the results back. (Which is essentially what a GUI event thread does, as I described way back...)

Maybe you are looking for

  • Problem using a Western Digital external drive

    All, I am using Oracle 11.2.0.1 32-bit Windows on Windows Vista Ultimate, in conjunction with McAfee Antivirus Plus. I have issues using an external Western Digital Elements USB drive, which has the Flash Recovery Area. Please note my Windows Backups

  • In IE, Error Occur: ClassNotFoundException:Orcale.XML.Paser.v2.XMLDocument

    I made a program which uses Orcale XDK to process XML, this program is not a Applet. And it run quite well. But then I modified it to Applet and it pass compile, and mak HTML contain this Applet, but when I open the page using IE, the error showing i

  • Quick time player hide

    the problem may be very silly, when i scroll down on my site page than the quick time player hide, although the music still play in the background . please reply ASAP

  • Pre-insert trigger is not firing after post built-in

    Hi, I have a 10g form in which Post built-in is used in When-button-pressed Trigger. After the post command I am checking some condition,by using the same record which I have posted.But it is not working. I have also put the message in the pre-insert

  • Adobe illustrator CS crashing

    Ok today when I went to use illustrator it crashed and would not open so I restarted the the power book and it still would not open.. so then I uninstalled illustrator and reinstalled it and it is still crashing... Anyone have any idea of how I can f