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

Similar Messages

  • 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

  • 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 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 destroy the worker thread

    My problem is I have a swing client which has 2 buttons, search and cancel. In search button I am creating a new worker thread which will be calling my EJBs method. Thus I have an event thread and a worker thread running. Now when I click cancel button I want to interrupt my worker thread and screen should enable the search button but what happens is when I click cancel button it still continues with the worker thread even though I am calling workerthread.interrupt() method and this results in showing the result of the EJB's method on the screen. how can I prevent the worker thread to stop executing the ejb's method and come back to normal mode.

    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

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

  • How to block the creation of a Sales Orders without a linked Purchase Order

    Hi. I'm trying to block the creation of a Sales Order that doesn't have a linked Purchase Order. The first thing I did is using the SBO Transaction Notification as follows:
    IF  @transaction_type = 'A' AND @object_type='17'
    BEGIN
         IF (SELECT PoPrss FROM ORDR WHERE DocEntry = @list_of_cols_val_tab_del) = 'N'
         BEGIN
              SET @error = 1
              SET @error_message = 'Purchase Order Missing...'
         END
    END
    This works good. I create the Sales Order, I tick the purchase order field on the logistics tab, I click Add, and then the purchase order window appears...
    Then, the problem begins... If I click the Cancel button, the purchase order is obviously not created, but the Sales Order is created.
    Can someone tell me how to block the creation of the sales order If the user press the cancel button on the purchase order window (and the purchase order is not created)
    As far as I can see, after clicking the add button in the sales order document, the Sales Order is created on the DB. If there's no way of blocking the creation of the Sales Order, can I avoid closing the purchase order window by the SBO_TransactionNotification? (if the purchase order has not been created)
    Thanks...

    Hi Yail,
    I think you can't close the purchase order with the stored procedure.
    Try to catch the Event when the user click on Cancel button.
    So you can list the vents with event logger : https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/ede3be37-0e01-0010-1883-cd1b5293473e
    You can block the cancel button and force the user to create the purchase order.
    Hope i help you
    Best regards
    Michael

  • How to block the Creation of Mulitple Excise Invoice in J1IS

    Hi Sap Gurs,
    Can any tell me how to block the System allowing  to Create One more Excise Invoice in J1IS against Same GI Material Document no (Ref Trans Type:MATD) for Outgoing Materials ie:Stock Transfer from One Plant to onother Plant by Mvt Type 351(Single Step Procedure)
    In SD, System is not allowing to Create One more Excise Invoive against One Billing Document Untill we Cancell the same.
    I want to make it like same for the above Issue.
    Pls check it in your system and give a Feed Back.
    Thanks in advance.
    Bye
    Sathish

    Hi Yail,
    I think you can't close the purchase order with the stored procedure.
    Try to catch the Event when the user click on Cancel button.
    So you can list the vents with event logger : https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/ede3be37-0e01-0010-1883-cd1b5293473e
    You can block the cancel button and force the user to create the purchase order.
    Hope i help you
    Best regards
    Michael

  • How to link the main site menu to an anchor on a subpage?

    How to link the main site menu (masterpage) to an anchor possition on a subpage? Is that possible. I would like the the contact menu to link to specific anchors  location contact FAQ hours. The way I do it now. I have to create seperate html pages, I would rather do it on one page. Thanks
    http://beta.tmj-sleep.ca/index.html

    Hello,
    To link a website Menu to anchors on any page in the website, you need to create a manual menu using the Menu Widget. You can change Menu to a manual Menu by clicking on the white arrow in Blue Circle which comes up at the top right of the Menu (Menu properties) and select the Menu type as Manual. Please have a look at the screenshot below :
    Now you can add change/add the text there and when you select the text/menu item then from the Hyperlink drpdown at the top in the toolbar, you can select the name of the anchor on any page of your website.
    Anchors are listed in Hyperlink dropdown in this format - Page Name:Anchor Name.
    Hope this helps.
    Regards,
    Sachin

  • How to block the cost center

    Dear Guru's
    Can any tell me how to block the cost center, can we detele which is having values. can we delete which is not having values
    Regards
    Chandra Sekhar Reddy.P

    Hi,
    Once you post actual values or any planning exists on this cost center you cant delete.
    To ristrict posting to cost you have two options.
    1.You can change validity period.
      change  end from 12/31/9999 to what ever date you want to stop posting(e.g. as of today 10/23/08)
    2. lock all postings to cost center on Control data tab in KS02.
    Thanks,
    Rau

  • How to block the GR against a PO

    Hi All,
    how to block the GR against a perticular PO item or full PO.
    I use "Delivery Complete" option in "Delivery" tab, but still it allow me to make the GR against the PO.
    I am waiting for the quick reply.
    Thanks & Regards
    Pankaj Garg

    delivery complete indicator willnot help u fully.what u can do is after selecting the delivery complete indicator change the quantity of the PO to what u have already received i.e. if ur po has 10 pcs and u have already received 4 pcs and dont want to receive any further quantity then change the PO quantity to 4 pcs.
    Again if u havent received any quantity against the PO then u can select the line items and select the block (key like) indicator or delete (dustbin like) indicator.
    regards,
    indranil

  • How to Block the material

    Hi friends,
    How to block the material ,
    what are the implecations if we block a material?
    Regards
    Krishna

    Hi,
    The best way is to keep the materail status with deleted or blocked for puchase / sales and need to maintain in the materail master.
    You cannot delete the material from material master until archiving but you can block that material for any procurement
    Goto Basic data 1
    X-plant matl status -
    01 Blocked for procment/whse
                                           02 Blocked for task list/BOM
                                           10 Blocked for MRP
    Select any one.
    Valid from  -
    Here you enter valid date from which the material should be blocked.
    So from this your material will be blocked for any PR/PO/any transactions related to Procurement
    BR,
    Krishna

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

  • How to Block the GRN,

    Dear Experts
                       How to block the GRN, to avoid the excess inventory for the particular  material.

    Hi Raja
    I assume that you are referring to stopping GRN of goods with resepect to the PO qty
    In that case If you want to stop the GR of more goods than the quantity ordered, you can use delivery
    tolerance settings in either material master data or purchase info record data.
    Regards
    Vikrant

Maybe you are looking for

  • Stock on hand at a point in time

    Hi Experts I am busy doing an inventory report in Crystal. I need to pull the stock on hand for all the items for each month (past 4 years, +-2500 items) At the moment, i am taking inqty - outqty where date <= (beginning of each month) My report is t

  • PR item Release with Workflow

    Hi All, If anybody has worked on PR item release with Work-flow please share the process ...i know how to set up the PR release strategy but not aware of Work-flow setting...If anybody has the document please share...... I searched a lot in the Forum

  • How do I unregister the phone

    I have sold my phone and need to know how I can unregister and register the new phone?

  • IPhone Cable....(dangerous?)

    Is anyone else having this problem with their iPhone cable? The wires are starting to show on mine and I don't really move my syncing port that much, only when I travel, I roll up the cable. Is this dangerous?

  • Migrate Data action hanging migrating from sql server to Oracle 10g

    Hi, I am currently migrating a SQL Server 2005 db to Oracle 10g using SQL Developer 1.2.1. I have created the migration repository, captured the SQL Server db objects, and created the target schema. There are about 109 tables captured. During Data mi