Access System.in / out several threads

Hi,
Trying to make my program work with command line input, but spawning a new thread to handle the user input mixes things up. I'm sure this is very basic, but can't find a solution. Tried to fumble around a bit by passing System.in as method argument to the new thread and by copying stuff along with PipedStreams, but no success.. Dont know if the new Console class would be nice for this, but i'm using jdk1.4.2 where its not yet included.
Could any one give me some pointers how to do this proper?
Thanks

Is the dummythread blocking on system.out or whats the problem?
Heres sample:
public class MultiThreadSystemOut
     public static void start()
          System.out.println("MultiThreadSystemOut.start");
          new ExternalSystemOut().run();
          new DummyThread().run();
          System.out.println("MultiThreadSystemOut.start: end");
     public static void main(String[] args)
          MultiThreadSystemOut.start();
public class DummyThread implements Runnable
     public void run()
          long t1 = System.currentTimeMillis();
          long t2 = t1 + (60 * 1000);
          int counter = 0;
          while(t2 - System.currentTimeMillis() > 0)
               System.out.println("DummyThread.run: running happily for "+counter+" times.");
               counter++;
               try
                    System.out.println("DummyThread.run: waiting");
                    Thread.sleep(5000);
               catch (InterruptedException e)
import java.io.IOException;
public class ExternalSystemOut implements Runnable
     public void run()
          try
               System.out.println("ExternalSystemOut.run");
               boolean run = true;
               while (run)
                    if (System.in.available() > 0)
                         byte[] byteBuf = new byte[System.in.available()];
                         System.in.read(byteBuf);
                         String input = new String(byteBuf);
                         System.out.println("ExternalSystemOut.run: got some "+input);
                         if (input.indexOf("/q") > -1)
                              System.out.println("ExternalSystemOut.run: quitting");
                              run = false;
          catch (IOException e)
               e.printStackTrace();
}Message was edited by: Imiro
Bummer, you should create Runnable like new Thread(runnable).start()... Topic closed.

Similar Messages

  • Using the distributed System.Transaction in several threads

    I'm using Oracle DB 11.2.0.1 and ODP.NET 2.112.2.0.
    I try to use the distributed transaction from System.Transaction namespace in several threads asynchronously. Here is the test console application. It creates new TransactionScope, creates 2 connections and opens them. At this time the transaction becomes distributed, because there are 2 opened connection in it. Then 2 INSERT commands are executed simultaneously in the same transaction (via Parallel.ForEach):
         class Program
              private static string ConnectionString = "MyConnectionString";
              private static void Main(string[] args)
                   cleanup();
                   for (int i = 0; i < 100; i++)
                        try
                             init();
                             run();
                             check();
                             Console.WriteLine("ITERATION {0} IS OK", i);
                        catch (Exception ex)
                             Console.WriteLine("ERROR AT ITERATION {0}: {1}", i, ex);
                             //break;
                        finally
                             cleanup();
              // main method
              private static void run()
                   using (var scope = new TransactionScope())
                        using (var connection1 = new OracleConnection(ConnectionString))
                        using (var connection2 = new OracleConnection(ConnectionString))
                             connection1.Open();
                             connection2.Open();
                             Transaction tx = Transaction.Current;
                             if (tx.TransactionInformation.DistributedIdentifier == Guid.Empty)
                                  throw new InvalidOperationException("tx.TransactionInformation.DistributedIdentifier == Guid.Empty");
                             var queries = new ConcurrentDictionary<OracleConnection, string>();
                             queries[connection1] = "INSERT INTO T1 VALUES ('AAA')";
                             queries[connection2] = "INSERT INTO T2 VALUES ('BBB')";
                             Parallel.ForEach(
                                  queries,
                                  pair =>
                                       using (var innerScope = new TransactionScope(tx))
                                            OracleCommand cmd = pair.Key.CreateCommand();
                                            cmd.CommandText = pair.Value;
                                            cmd.ExecuteNonQuery();
                                            innerScope.Complete();
                        scope.Complete();
              // check results
              private static void check()
                   using (var connection = new OracleConnection(ConnectionString))
                        connection.Open();
                        OracleCommand cmd = connection.CreateCommand();
                        cmd.CommandText = "SELECT COUNT(1) FROM T1";
                        int n1 = Convert.ToInt32(cmd.ExecuteScalar());
                        if (n1 != 1)
                             throw new Exception("COUNT(T1) != 1");
                        cmd.CommandText = "SELECT COUNT(1) FROM T2";
                        int n2 = Convert.ToInt32(cmd.ExecuteScalar());
                        if (n2 != 1)
                             throw new Exception("COUNT(T2) != 1");
              // initialization          
              private static void init()
                   executeCommands(
                        "CREATE TABLE T1 ( V1 VARCHAR2(100) )",
                        "CREATE TABLE T2 ( V2 VARCHAR2(100) )"
              // cleaning up
              private static void cleanup()
                   try
                        executeCommands(
                             "DROP TABLE T1",
                             "DROP TABLE T2"
                   catch
              // helper method executing some commands
              private static void executeCommands(params string[] queries)
                   using (var connection = new OracleConnection(ConnectionString))
                        connection.Open();
                        OracleCommand cmd = connection.CreateCommand();
                        foreach (string query in queries)
                             cmd.CommandText = query;
                             cmd.ExecuteNonQuery();
    It works fine mostly. But sometimes an exception is thrown at check method ("COUNT(T1) != 1" or "COUNT(T2) != 1"). So one of commands isn't enlisted into the transaction. And when I change commands to insert values into the same table (and also change check method), a deadlock sometimes occurs.
    Where am I doing wrong?
    P.S. There are no errors on Oracle 9.

    The same question after a year: are you going to fix the issue?

  • How to make several threads do smth at the same time?

    Hello!
    Is there a way to make several threads guaranteedly do something at exactly the same time? The code below creates two identical Random objects with approximately 90% probability, in 10% cases Random's are different (Random constructor takes current system time as its argument). But how to ensure it 100%?
    import java.util.*;
    public class SyncThreads extends Thread {
         static Date DATE;
         static long CURRENT_TIME;
        public static void main(String args[]) {
              DATE = new Date();
              CURRENT_TIME = DATE.getTime();
                    new SyncThreads().start();
              new SyncThreads().start();
         public void run()
              try
                   Date thread_date = new Date();
                   long diff = thread_date.getTime() - CURRENT_TIME;
                            //sleeping untill it's 1 second since the 1st line of main() executed
                   sleep(1000 - diff);
                   int r_i = new Random().nextInt();
                   System.out.println(r_i);          }
              catch (InterruptedException e)
                   System.out.println("Find out what InterruptedException is!");
    }

    and even if the PC has multiple processors you are still not guaranteed that it will run the seperate threads at the same exact moment. The JVM for the platform would have to be optomized to make use of multiprocessors for starters, and even if it is it still doesn't guarantee it, the way the OS handles applications (i.e. the JVM) and the way the JVM handles multithreads all will have implications on whether or not two threads actually truly run simultaniously.

  • Access System Resources using Java Applet via Java Script

    Hello
    I can access my Applet public methods (and this methods access system resources) via Java Script if I do the following: System.setSecurityManager(null);However, I'm making this post because I don't like this solution.
    Supposedly, setting the SM to null is like making the Applet (which is signed and was accepted by the user via a prompt from the browser) behave like a normal Java program that has no restrictions. (http://java.sun.com/docs/books/tutorial/essential/environment/security.html, second paragraph)
    However, this feels like a workaround of something that is supposed to be there (the SM).
    Also, if I make the methods invocation from inside the applet (using swing buttons and textboxes for example) I can use the standard SM without no problems.
    From my readings, the problem regarding Java Script invocation, comes from the fact that the Java Script is not a secure (not signed) source (because you can invoke public methods the way you wish from it i guess) on the contrary to the applet methods invoked by the buttons.
    Possible solutions I found in the web range from using the public static Object doPrivileged(PrivilegedAction action) method or imaginative things like creating new threads on the public method that call the private methods that access the system resources (supposedly because the new thread runs under the safe environment of the applet)
    I almost got a glimpse of hope with this post http://forums.sun.com/thread.jspa?threadID=5325271&tstart=0
    However, none of these solutions worked, the only results were with the setResourceManager(null)So, any one can contribute with a solution for this? Should I keep trying to find a solution other then the one I already have?
    Regards
    Cad

    1. yes
    2. yes
    Note for 2. the converter will run the applet with SUN jre for sure if the user has IE.
    IE will use the ActiveX technology to run the applet (as with Macromedia Flash).
    For Netscape I am not sure, but I would think Netsape will use the plug in provided by
    SUN.
    Note for SUN jre 1.3. If this applet is to be used within a company that uses a proxy with
    ntlm authentication the 1.3 applet cannot connect (to the Internet) through this proxy since
    ntlm athentication is supported since j2re1.4.2_03. There is one version before that but
    that one will pop up a window asking for the user's domain account and password wich
    is both lame and crappy.
    As for the IE settings, IE has a default setting that askes users the "do you trust"
    queston for AciveX controls within the Internet securety zone (tools -> internet options
    -> security).
    Sincy anybody can make ActiveX controls (allso sign them) a user that has a problem
    to find the "no" button will sooner or later install a malicuous ActiveX control (spy ware
    or a virus).
    If this user's desktop is within your company's network it will cause serious harm.
    This is why most company's disable this by changing the default internet expolorer
    settings. Since I assume you are writhing this applet to be used by a company I allso
    assumed that company has someone to maintain the desktops. In that case I
    assume that person would want to control the security within the SUN jre instead of
    letting the user deside what to trust and what not.

  • Problems while accessing System Configuration

    Dear All,
    I am accessing System Configuration link thru System Administration--> System Configuration using J2EE_ADMIN as the user, even though i have given most of the authorisations it still gives me a access denied javascript error. can anyone please let me know for which authorisations i need to check
    regards
    Vinay

    Its not necessary that if you hav super admin role that you can access  the system information.You need to hav the the credentials of the "administrator".
    you can find out the system configuration details from the url
    http:<hostname:portno>/index.html
    click on system configuration.
    you can accesses those details if you are having  administrator role only.If u dont have it contact your portal admin or basis people they can help you out.

  • CSA - Access system functions?

    Can anyone else post any examples of times they needed to make an exception for allowing a certain application to access system functions? I keep getting several trips of the rule for accessing system functions, and I'm sure there is no attack or spyware on the machine. The only event I can manually replicate is when Windows Media Player tries to access license files online ("CreateThread").
    Just curious to see if anyone else has had to build an exception or allow rule for accessing system functions.

    it might help to explain the context of why I'm trying to do this too, so here goes all...
    I've seen several event logs where Rule 886 was tripped. Rule 886 is a System API rule in the General Application Permissions - all security levels rule module. The details of the rule are that it queries the user whenever a Network Application, MS explorer, rundll32.exe, or any media application, tries to "access system functions from code executing in data or stack space", which is listed under Atypical system behavior.
    Most of these events occur late at night, and appear to be something dealing with updates or spyware scans. I haven't yet been able to isolate or replicate those. The only time I've been able to manually trip this rule is when Windows Media Player attempts to download license files for a CD/song, it will access "CreateThread" system function.
    Now, the reason I'm worried about this is that end users are going to throw up their hands at the query, which says "Application xxxxx.exe is attempting to access System Function zzzzz. Would you like to allow this?". They're going to either have no idea what to do and call the Helpdesk or they're going to take a guess at what to do and could cause something bad.

  • When sending e mails, w attch the system stalls out just "spinning, not attaching, does not happen with exploere

    When attempting to send e-mails w/ attacments, the systems stalls out, just keeps spinning, problem does not occur with exporer.
    Also when trying to attch pics, same thing

    No need to be inhappy.
    iPhoto Menu -> Preferences -> Accounts ->
    Delete and recreate your email settings.
    Alternatively, use Apple's Mail for the job. It has Templates too - and more of them.
    There's no need to go through that exporting routine. Your iPhoto Library is available in every app.  See this for more:
    For help accessing your photos in iPhoto see this user tip:
    https://discussions.apple.com/docs/DOC-4491

  • How can I show thru jlabel a variable that is modfied by several threads?

    Dear all,
    This is my problem, I have a variable, lets say m_money, m_money is been constantly modified by severeal threads, and it is also showed on my user interface using a jlabel componet, lets say m_jlabel_money. You have to take into account that if you want modify the state of a swing object with different threads you have to use something like invokeLater or another Swing utilities.
    My question is how should I program my threads to modify m_money and m_jlabel_money at the same time without multithreading inconsistency?
    I did this, but I am not sure if this is correct:
    // function called by my threads
    public synchronized void SetSaldoUsuarioMoneda(double money) {
              m_money=money;
              SwingUtilities.invokeLater(new ModifyJlabelState ());
    //funtion which modify jlabel statte
         private class ModifyJlabelState implements Runnable {
                  public void run() {
                        m_label_saldo.setText(m_money);
         }Is this correct?
    Should I pass m_money to ModifyJlabelState thru its constructor or should I read m_money from ModifyJlabelState?
    Is synchronized required or is it no sense?
    Is this a better way or is going to fail bacause money variable may be different?
    // function called by my threads
    public synchronized void SetSaldoUsuarioMoneda(double money) {
              m_money=money;
              SwingUtilities.invokeLater(new ModifyJlabelState (money));
    //funtion which modify jlabel statte
         private class ModifyJlabelState implements Runnable {
                      private double m_money;
                    public ModifyJlabelState(double money) {m_money=money;}
                  public void run() {
                        m_label_saldo.setText(m_money); // this m_money is/was what we had when we created this instance, so is this correct?
         }Well, I would like to know your opinions about this, because I don't know how should I solve this.
    Thanks a lot.
    Edited by: Ricardo_Ruiz_Lopez on Jun 24, 2008 1:01 AM
    Edited by: Ricardo_Ruiz_Lopez on Jun 24, 2008 1:02 AM

    Your first approach is incorrect. You either need to synchronize the 'setText' call or make m_money volatile.
    Your second approach will work with the caveat that the value displayed on the label may be slightly out-of-date.

  • Can't access System Preferences in Spaces

    Quite frequently I find myself unable to access System Preferences.
    I think it may be a Spaces issue and I think it may happen if I close the System Preferences window.
    If I Option-Command-Esc, the window shows System Preferences is running. But force quitting System Preferences has no effect.
    If I Command-Tab, I see System Preferences in the row of icons. However selecting this icon has no effect, the System Preferences window does not come to the front.
    Of course I can't open Spaces to try to resolve the problem because it is a System Preference.
    The only solution I have found is to Logout and log back in.

    Oops, never mind. I have a Wacom tablet connected to my Mac, and turns out that the system prefs window was showing up on that screen instead of my main display.
    For future reference, is there a way to delete a post such as my first one?

  • How to access System properties in xml file

    hi,
    i want to read system properties in my xml file using ${} .
    I tried it but did not find any way.But when i use log4j if i set some variable in
    System properties that properties is read by the log4j.properties .
    I am writing a simple program that read a xml properties file file
    try {
                props   = new Properties();
                fis     = new FileInputStream(xmlFile);
                props.loadFromXML(fis);
    }before reading this file i set some properties and accessing this properties from that xml .but i cant.
    Thanks

    sabre150 wrote:
    fun_with_java wrote:
    can you give some example?Not really - I would have to write the code for you and I'm not getting paid for writing your code.Thanks for your kindness.
    I dont ask you to write the code.Need some help to start it .Actually i dont have knowledge that
    whether xml file automatically read it or i have prase the system property manually. Now i got the way to
    access system property in xml..
    Ok thanks again..
    Thanks & Regards

  • Error while trying to access system information for AS Java

    Hi,
    I´m not sure if this is the correct forum so if I'm wrong please let me know to move it to the correct one.
    We are facing an extrange behavior when trying to access System Information in an AS Java, every time we try to access the link the following error shows up:
    Error - ID018236: Cannot instantiate bean. java.lang.ClassNotFoundException: com.sap.engine.monitor.infoapp.SystemInfo
    the complete error shows:
    Found in negative cache -
    Loader Info -
    ClassLoader name: sap.com/tc~monitoring~systeminfo Parent loader name: References: common:service:http;service:servlet_jsp service:ejb common:service:iiop;service:naming;service:p4;service:ts service:jmsconnector library:jsse library:servlet common:library:IAIKSecurity;library:activation;library:mail;library:tcsecssl library:ejb20 library:j2eeca library:jms library:opensql common:library:com.sap.security.api.sda;library:com.sap.security.core.sda;library:security.class;library:webservices_lib;service:adminadapter;service:basicadmin;service:com.sap.security.core.ume.service;service:configuration;service:connector;service:dbpool;service:deploy;service:jmx;service:jmx_notification;service:keystore;service:security;service:userstore interface:resourcecontext_api interface:webservices interface:cross interface:ejbserialization library:tcjmx library:sapxmltoolkit library:tcSLUTIL Resources: /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoringsysteminfo/servlet_jsp/sap/monitoring/root/WEB-INF/classes /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoringsysteminfo/servlet_jsp/sap/monitoring/root/WEB-INF/lib/jstartupapi.jar /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoringsysteminfo/servlet_jsp/monitoring/root/WEB-INF/classes /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoringsysteminfo/servlet_jsp/monitoring/work /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoringsysteminfo/servlet_jsp/sap/monitoring/work /usr/sap/QBW/DVEBMGS03/j2ee/cluster/server0/apps/sap.com/tcmonitoring~systeminfo/servlet_jsp/sap/monitoring/root/WEB-INF/lib/jstartupimpl.jar Loading model: {parent,references,local} -
    Any idea about what is happening is appreciated.

    check with this links too
    http://hostname:port/sap/monitoring/SystemInfo
    http://hostname:port/monitoring/SystemInfo
    Implementing this note should solve your problem
    Note 1281251 - System information exception: Connection is invalid
    and also check
    Note 1233282 - Fixed URL of System Information application on Start page
    Thanks,
    Surendra

  • Access Denied error (0x80070005) when trying to access System Protection or Restore

    When I attempt to access System Protection or System Restore, I get an error message "Access Denied- (0x80070005)". I hope someone knows a fix for this problem.

    Satellite P205-S7476 
    When I attempt to access ... System Restore, I get an error message "Access Denied- (0x80070005)".
    That probably indicates corruption in the restore points. The only way to fix it is to turn System Restore off and then on again. Unfortunately, that remove all the existing restore points.
       Turn System Restore on or off
    -Jerry

  • In F-53 system listing out wrong open item

    Hi Guru's,
    while making outgoing payment in F-53 system listing out 'A001' & 'B001' company code open item rather than 'A001' company code open item. In the selection screen we are giving only company code 'A001'.
    This vendor has been extended for both the company code.
    Could you please help me to bring selection screen company code open item only.
    with regards,
    Jammy

    in f-53 after giving all the required information in document header bank account number and amount click on process open items without giving the vendor code on the main screen of f-53
    there check which company code is selected and then give the vendor code and co code and process again
    and let me know if you are facing the same problem again
    Also check the vendor open items for each co code in FBL1N

  • I can't accessed system recovery options after the repairing process was interrupte​d.

    although it's not my PC, i'm still concern about it (it's actually a public computer in our library). I actually tried to repair it using the system recovery options of windows 7 with thinkvantage technoliogies  but i interrupt it because maybe someone will caught me and i will be mistakenly be liable. and the result is after i restared it, it restarts over and over again, with BSOD appearing for a split second. i tried to use disable autorestart on system failure feature, and i saw the BSOD. but the real issue is i can't go through the recovery options, only until the part when i'm asked to select a keyboard input method, then the next part is this message: "You must log in to access System Recovery Options. If you are having trouble logging in, please contact your computer administrator for assistance. Click OK to restart the computer." anyway, this is the BSOD says: 
    A problem has been detected and windows has been shut down to prevent damage to your computer.
    If this is the first time you've seen this stop error screen, restart your computer. If this screen appears again, follow these steps:
    Disable or uninstall any anti-virus disk defragmentation  or backup utilities. Check your hard drive configuration, and check for any updated drivers. Run CHKDSK /F to check for hard drive corruption, and then restart your computer.
    Technical in formation:
    *** STOP: 0x00000024 (0x00000000001904, 0xFFFFFA800690D840, 0XFFFFFFFFC0000102, 0x0000000000000000)
    I hope this problem will be solved as much as possible.  thank you in advance. and i also don't know what model of this Lenovo all-in-one PC is. but i think this is 3318F9U, and its i forgot its BIOS version, and i don't know how to access it. and also, i'm not sure if there's a preloaded Superfish in this all-in-one PC, maybe the vulnerability started it. because i recently read an article regarding the Superfish's vulnerability.

    Hello and welcome,
    Please remeber that this is a peer-to-peer forum (users helping each other) not the Lenovo support site.  There is some Lenovo presence, but  if you need urgent support, please try your local support office:
    Philippines
    THINK-branded products
    Tagalog, English
    1-800-8908-6454 (GLOBE subscribers), 1-800-1441-0719 (PLDT subscribers)
    Z.
    The large print: please read the Community Participation Rules before posting. Include as much information as possible: model, machine type, operating system, and a descriptive subject line. Do not include personal information: serial number, telephone number, email address, etc.  The fine print: I do not work for, nor do I speak for Lenovo. Unsolicited private messages will be ignored. ... GeezBlog
    English Community   Deutsche Community   Comunidad en Español   Русскоязычное Сообщество

  • How do I set up the magic trackpad when I can't access System Preferences

    Bought a new iMac and Magic Mouse.    After initial installation, decided to swap mouse for the Magic Trackpad.
       Trackpad is turned on but I am unable to access System Preferences since my iMac was paired with the Magic Mouse.  I don't have another USB mouse to complete the pairing.  Any suggestions?   Thank You.

    Nancy,
    If you have the bluetooth icon in the menubar, you can reach that and open bluetooth preferences by
    pressing FN CNTL F8.  This will move focus to the right side of the menubar, then arrow across and down to get to the options you need.  Press the spacebar for "enter".
    Regards,
    Captfred

Maybe you are looking for