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

Similar Messages

  • 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

  • How to make  the main payload be sent as mail body

    Hi,
    Currently, I want to send out a mail with several attachments by Mail adapter. And <b>the main payload</b> should be sent out as <b>mail body</b> instead of attachment. I know by default, the main payload is also sent as a attachment. So I used the module AF_Modules/MessageTransformBean to make the main payload be sent as mail body instead of attachment. It does work in case there's no attachment to be sent. However if I want to send<b> a mail with several attachments</b> (the attachment is created in my own adapter module using method message.createPayload()), in this case if I use the module AF_Modules/MessageTransformBean, the main payload is sent as mail body , however meanwhile, it is also sent as a attachment. And the attachment I created is also sent as attachment. This is not expected by me. In this case, I wish <b>the main payload</b> is <b>only sent as mail body</b> and <b>other payload</b> created by me as attachment.
    Do you have any idea about it?
    Thanks

    hi
    go through this links:
    /people/michal.krawczyk2/blog/2005/11/23/xi-html-e-mails-from-the-receiver-mail-adapter
    /people/michal.krawczyk2/blog/2006/02/23/xi-dynamic-name-in-the-mail-attachment--pseudo-variable-substitution
    Thanks

  • How to make the session to wait until other session get closed successfully

    Hi ,
    In my program , I am calling sql loader and after that I am opening a session and inside that I am calling stored procedure which validates the data.
    above calling of sql loader and stored procedure is done inside the shell script i.e .prog file which is registerd as host concurrent program.
    Here i am facing the problem like when two files are processed with same content then second file content's are not erroring out as duplicate though there is a duplicate validation exist inside the procedure. IF I call dbms_lock.sleep(60) then it is working and sencond file are records are error out with duplicate error message. but this is working only for small data files.
    Please suggest me how to make the session to come out successfully then only i can open other sesssion .
    Thanks
    Raghav

    user5853450 wrote:
    Hi ,
    In my program , I am calling sql loader and after that I am opening a session and inside that I am calling stored procedure which validates the data.
    above calling of sql loader and stored procedure is done inside the shell script i.e .prog file which is registerd as host concurrent program.
    Here i am facing the problem like when two files are processed with same content then second file content's are not erroring out as duplicate though there is a duplicate validation exist inside the procedure. IF I call dbms_lock.sleep(60) then it is working and sencond file are records are error out with duplicate error message. but this is working only for small data files.
    Please suggest me how to make the session to come out successfully then only i can open other sesssion .
    Thanks
    RaghavFor starters you could use external tables rather than SQL*Loader and then you could keep all the control on the database side of things rather than relying on an external utility. The external tables will give you all the functionality of SQL*Loader but all you to just read the data using SQL select statements instead and cut out all the shell script dependency.
    Alternatively you could also look at Job Chaining...
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14214/chapter1.htm#FEATURENO05574

  • How to hold the main thread, till response is received from the server?

    I have a program in which the GUI client(View program in Swings) sends a request to server (Manager program) , and waits for the response from Manager.
    The method used is waitForResponse() as follows
    <code>
    private void waitForResponse()
    m_blWaitFlag=true;
    //after response from manager m_blWait flag is set to false.
    while (m_blWaitFlag)
    try
    Thread.sleep(500);
    }catch(Exception r_ex)
    </code>
    And in notifyResponse() method, the wait flag is set to false
    as in,
    <code>
    public void notifyResponse(VcvResponse r_objResponse)
    m_blWaitFlag = false; //this line makes the thread to come out of the wait mode.
    </code>
    When I click a menu item, this request is sent and there is a wait for a response from manager.
    The problem is , this kind of waiting makes the system slow, and grey patches are seen immediately after clicking a menu item.
    Are there other ways of waiting??
    Thanks in advance

    When I click a menu item, this request is sent and there is a wait for a response from manager.This means you are using the GUI thread to send the request.
    The problem is , this kind of waiting makes the system slow, and grey patches are seen immediately after clicking a menu item.This means the GUI thread is waiting for the response. No GUI updates can occur while it is waiting.
    Are there other ways of waiting??Use another thread. e.g the main as you suggested. If you are using a callback, why do you have a thread waiting at all? WHy not do the things you would do when a response comes back in the call back?

  • How to make the main window's table size fixed?

    Hi all,
       when i have a single line item, the size of table in main window is getting reduced. Its size is varying according to number of line items. Is not is possible to keep the size of table fixed even you have single line item?
    Regards,
    Bipen

    Hi,
    You need to create a dummy template of fixed size and do not use lines for the main window table use the template. this will overlap with the window height.
    If you want tro display something then pass the field based on some condition  on end of the table
    Regards
    Shiva

  • How to control the main thread?

    public static void main(String args[]) {
    Thread t = Thread.currentThread();
    System.out.println("Current thread: " + t);
    In the above code, i want to know more about currentThread() method...
    if i execute, i get an error message,can anyone help me in this regard?

    When i execute the program, the program has an output
    as below:
    current thread:[main,5,main]
    But a window opens telling that there is some error
    in the program...
    Why does it happen so?What is the EXACT text of the error message?

  • How to make the print command wait until form is rendered.

    This is an ongoing issue that so far I haven't been able to figure out how to fix, so I'm hoping that someone will have a good idea or work around. I'm working in LiveCycle Designer ES v8. using JavaScript.
    I have to include a feature that allows the user the choice to print out a dynamic form to fill out by hand. So I've created a button that asks if this is what they want to do, if they answer "Yes", then several things are scripted to happen. All data is reset, some subforms and pages are made visible, while other subforms are hidden, and text fields are expanded. This causes the form to expand from one page to 15 pages. Then it prints using this command:
              xfa.host.print(1,   
    "0", (xfa.host.numPages -1).toString(), 0, 1, 0, 0, 0);
    The problem is that when the print dialogue box appears, the Print Range is always set to less than the total number of pages. It looks like that the print commands fires before the form has completed rendering. This isn't a big deal since the user can click to set the Print Range to "All" which will print all 15 pages. The problem is that most people don't read the dialogue box. They click "okay" and end up with their form cut off.  Then I get phone calls that my form doesn't work.
    Is there anyway to delay the print command until everything has finished rendering? Or set the Print Range to always go to "All"?
    Thanks in advance for your help with this.

    It sounds like you'd be fine if you just separated the print function from your "Yes" button. It will require a 2nd button click from the user but that would be the only inconvenience.

  • Using non-blocking NIO, need Main Thread wait?

    I'm trying to utilize the New IO libraries to create a simple url check application. The application just tests return codes to make sure the list of urls I have are still valid.
    I'm using the NIO libraries because I had problems with the URLConnection object hanging when I ran into a url where the server never replied. It just sat there waiting for a reply.
    Now I have a new problem, the connection to the web server is now in a new thread and I need to wait for the connection to finish before using it. I can't figure out how to make the main app wait for the connection. All of the documentation I find for the Wait() method refers to threads and I can't find how to refer to the main application thread.
    Any suggestions?
    Josh

    Ok, this is were I have some gaps in my Java knowledge. How do I wait for OP_CONNECT to fire. Is it like setting up a ActionListener but for a non-visual object?
    Also what do you mean when you refer to deregistering it?
    You don't need to explain everything. I would be happy if I was just pointed at the appropriate pages and I'll do the leg work.
    Josh
    If you're using NIO the connection can be handled in
    the same thread as the I/O. Just wait for OP_CONNECT
    to fire, deregister it, and away you go.

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

  • How to find the main window?

    Hi, can someone help me. I cant find the main multi track window. Ive looked in the window drop bar and searched with no luck and its starting 2 get annoying. Please any info would help

    I got it from a mate who's doing a music degree. Its the educational version its authentic. I was having problems with it just shutting down on me in the middle of a session so I re-installed the programme then when i ran it ther were no windows. I had to click on the window bar to make them appear but i dont know how th make the main multi track window appear? I installed the patch but still no change. Its probably somthing i have to open ye?

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

  • I have 10 UiWebView to load different charts and maps on an iPad,using UIScrollView to scroll through each page, problem is on loading of each UiWebView my UiScrollView does not scroll smoothly to other pages horizontally,so how to make the scroll smooth?

    I have 8-10 UiWebView's  to load different charts and maps on an iPad, i am using UIScrollView to scroll through each page, problem is while loading of each UiWebView my UiScrollView does not scroll smoothly to other pages horizontally, my query is can i load UiWebView on background and how to make sure the scoll of pages is smooth, even though the loading of UiWebViews may take time.
    Note :i have tried disabled scrolling on webview, so when i scroll on the page  the scroll event will be of UiScrollView, so believe no conflict with UiWebView.
    also in ios 6 i read about suppressesIncrementalRendering = True but i want to support ios5, also as UiWebViews are said to be running on main thread by default, i suspect when loading of webViews and when user tries to scroll the page, the main thread is busy, but i want the scroll of the page to be smooth  even though the loading of UiWebViews may take time.

    You will probably get a faster and more accurate answer if
    you repost in the Developers Forum.

  • JLabel in JTextPane - how to make the JLabel be highlightable

    Hi,
    This follows on from this post :
    http://forum.java.sun.com/thread.jspa?threadID=741036&tstart=0
    I'm inserting a JLabel into a JTextPane, and want it to look like the other text there. However when you select the text, the JLabels don't have the highlight painted on them. Does anyone know how to make the highlight be painted over the label?
    I've tried looking at the Highlighter, HighlightPainter classes but as yet no joy.
    thanks a lot,
    Tom

    If I understand what you're after you may find the following will achieve it:
    ((DefaultHighlighter)textPane.getHighlighter()).setDrawsLayeredHighlights(false);Don't ask me why, though!!
    Hope this helps.

  • How to make jdbc code thread safe

    Iam using jsp to connect to the data base how to make it is thread safe

    ch.vasu07 wrote:
    Iam using jsp to connect to the data base how to make it is thread safeYou should not be connecting to a database in a JSP. Do that on the server side. JSPs should be pure view.
    Learn JSTL and keep scriptlet code out of your JSPs.
    %

Maybe you are looking for

  • Photosmart 6510 e-ALL-IN-ONE Series offline

    I can't get my 6510 all in one to go back on-line.  I have windows 7 on my hp laptop and use my android phone as my wireless connection - this has worked perfectly for the past two years.  I ran a wireless network test and the printer indicates PASS

  • Keyboard shortcut...How Do I delete hundreds of pages at once?

    I have a spreadsheet imported from an Excel spreadsheet. The sheet is composed of 374 pages most of which are blank...I only need the first two for the time being? How do I select the first row and then go to the last row so I can highlight all and d

  • Itunes on new PC nighmare!

    I have recently bought a new lap top and before this was running two ipods from same PC. I used to open up the different librarys by holding down the shift key. What has happend is I seem to have successfully transferred the music files and have the

  • In OUT Bound of a Jaxws provider, how can we stop the provider invoking its endpoint and send a response back?

    Hi One & All While we are working on Delegate(provider) for JAXWS client handler in Weblogic10 , we have some technical issues and need some assistance. Problem Description In OUTBound of a provider, how can we stop the provider invoking its endpoint

  • SSRS Slow to load in IE

    Have a really strange problem with Reporting Services 2008 RTM.  If I try to go to the main URL http://servername/Reports/ in IE it takes a long time to load (15-20 seconds), same thing happens if I navigate directly to a report.  The rest of that se