Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

In this page you can find the example usage for java.lang Thread start.

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil.java

public static int runInstances(final CloudControllerClient client, final LoadBalancerContext context,
        final String domain, final String subDomain, int diff) {

    int successfullyStartedInstanceCount = diff;

    if (context == null) {
        // can't help
        return 0;
    }/*from  w w w.jav a 2 s  .com*/

    while (diff > 0) {
        // call autoscaler service and ask to spawn an instance
        // and increment pending instance count only if autoscaler service returns
        // true.
        try {
            String ip = client.startInstance(domain, subDomain);

            if (ip == null || ip.isEmpty()) {
                log.debug("Instance start up failed for " + domainSubDomainString(domain, subDomain));
                successfullyStartedInstanceCount--;

            } else {
                log.debug("An instance of " + domainSubDomainString(domain, subDomain) + " is started up.");
                if (context != null) {
                    context.incrementPendingInstances(1);
                }
            }
        } catch (Exception e) {
            log.error("Failed to start an instance of " + domainSubDomainString(domain, subDomain) + ".\n", e);
            successfullyStartedInstanceCount--;
        }

        diff--;
    }

    if (successfullyStartedInstanceCount > 0) {

        Thread stateChecker = new Thread(new PendingInstancesStateChecker(context, domain, subDomain,
                successfullyStartedInstanceCount, context.getRunningInstanceCount(), client));
        stateChecker.start();
    }

    return successfullyStartedInstanceCount;
}

From source file:com.healthmarketscience.rmiio.RemoteIteratorTest.java

public static List<List<TestObject>> mainTest(final boolean sendEmptyList, final boolean doAbort,
        final boolean noDelayAbort, final List<Throwable> clientExceptions,
        final List<AccumulateRemoteStreamMonitor<?>> monitors) throws Exception {

    ObjectServer server = new ObjectServer();
    final RemoteObjectServer stub = (RemoteObjectServer) RemoteStreamServerTest
            .simulateRemote(UnicastRemoteObject.exportObject(server, 0));
    LOG.debug("Server ready");

    LOG.debug("Sleeping 3000 ms...");
    Thread.sleep(3000);//from  www. java  2s .co m

    LOG.debug("Running tests");
    Thread clientThread = new Thread(new Runnable() {
        public void run() {
            clientExceptions.addAll(ObjectClient.main(stub, sendEmptyList, doAbort, noDelayAbort, monitors));
        }
    });
    clientThread.start();
    clientThread.join();

    LOG.debug("Unexporting server");
    UnicastRemoteObject.unexportObject(server, true);

    return server._recvdObjectLists;
}

From source file:com.tc.process.Exec.java

@SuppressWarnings("resource")
public static Result execute(final Process process, String cmd[], String outputLog, byte[] input,
        File workingDir, final long timeout) throws Exception {
    final AtomicBoolean processFinished = new AtomicBoolean();
    if (timeout > 0) {
        Thread timeoutThread = new Thread() {
            @Override/*  www . ja  va 2  s  .c  o  m*/
            public void run() {
                ThreadUtil.reallySleep(timeout);
                if (!processFinished.get()) {
                    process.destroy();
                }
            }
        };
        timeoutThread.start();
    }

    Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream());

    StreamCollector stderr = null;
    StreamCollector stdout = null;

    FileOutputStream fileOutput = null;
    StreamAppender outputLogger = null;

    String errString = null;
    String outString = null;

    try {
        if (outputLog != null) {
            errString = "stderr output redirected to file " + outputLog;
            outString = "stdout output redirected to file " + outputLog;
            fileOutput = new FileOutputStream(outputLog);
            outputLogger = new StreamAppender(fileOutput);
            outputLogger.writeInput(process.getErrorStream(), process.getInputStream());
        } else {
            stderr = new StreamCollector(process.getErrorStream());
            stdout = new StreamCollector(process.getInputStream());
            stderr.start();
            stdout.start();
        }

        inputThread.start();

        final int exitCode = process.waitFor();
        processFinished.set(true);

        inputThread.join();

        if (outputLogger != null) {
            outputLogger.finish();
        }

        if (stderr != null) {
            stderr.join();
            errString = stderr.toString();
        }

        if (stdout != null) {
            stdout.join();
            outString = stdout.toString();
        }

        return new Result(cmd, outString, errString, exitCode);
    } finally {
        closeQuietly(fileOutput);
    }
}

From source file:com.nokia.dempsy.mpcluster.zookeeper.ZookeeperTestServer.java

private static TestZookeeperServerIntern startZookeeper(Properties zkConfig) {
    logger.debug("Starting the test zookeeper server on port " + zkConfig.get("clientPort"));

    final TestZookeeperServerIntern server = new TestZookeeperServerIntern();
    try {/*  www  .  j a  v a 2s  .c  om*/
        QuorumPeerConfig qpConfig = new QuorumPeerConfig();
        qpConfig.parseProperties(zkConfig);
        final ServerConfig sConfig = new ServerConfig();
        sConfig.readFrom(qpConfig);

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    server.runFromConfig(sConfig);
                } catch (IOException ioe) {
                    logger.error(MarkerFactory.getMarker("FATAL"), "", ioe);
                    fail("can't start zookeeper");
                }
            }
        });
        t.start();
        Thread.sleep(2000); // give the server time to start
    } catch (Exception e) {
        logger.error("Can't start zookeeper", e);
        fail("Can't start zookeeper");
    }
    return server;
}

From source file:com.textocat.textokit.commons.io.ProcessIOUtils.java

/**
 * @param proc process which input stream will receive bytes from the
 *             argument input stream//from  w ww . j  ava2  s  .com
 * @param in   input stream. Note that it is closed at the end.
 */
public static void feedProcessInput(Process proc, final InputStream in, final boolean closeStdIn)
        throws IOException {
    final OutputStream procStdIn = proc.getOutputStream();
    final List<Exception> exceptions = Lists.newLinkedList();
    Thread writerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                IOUtils.copy(in, procStdIn);
                if (closeStdIn) {
                    procStdIn.flush();
                    closeQuietly(procStdIn);
                }
            } catch (Exception e) {
                exceptions.add(e);
            } finally {
                closeQuietly(in);
            }
        }
    });
    writerThread.start();
    try {
        writerThread.join();
    } catch (InterruptedException e) {
        // do nothing, just set flag
        Thread.currentThread().interrupt();
    }
    if (!exceptions.isEmpty()) {
        Exception ex = exceptions.get(0);
        throw ex instanceof IOException ? (IOException) ex
                : new IOException("Unexpected exception in writing thread", ex);
    }
}

From source file:src.gui.ItSIMPLE.java

/**
 * @param argsu//w w  w .ja  v  a 2s.com
 */
public static void main(String[] args) {

    //get CommonDatapddlVer
    Document commonDoc = null;
    try {
        commonDoc = XMLUtilities.readFromFile("resources/settings/commonData.xml");

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (commonDoc != null) {
        commonData = commonDoc.getRootElement();
    }

    // Get settings from itSettings.xml
    org.jdom.Document itSettingsDoc = null;
    try {
        itSettingsDoc = XMLUtilities.readFromFile("resources/settings/itSettings.xml");
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    if (itSettingsDoc != null) {
        itSettings = itSettingsDoc.getRootElement();
    }

    // Get planners from itPlanners
    org.jdom.Document itPlannersDoc = null;
    try {
        itPlannersDoc = XMLUtilities.readFromFile("resources/planners/itPlanners.xml");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (itPlannersDoc != null) {
        itPlanners = itPlannersDoc.getRootElement();
    }

    // Get validators from itValidators
    org.jdom.Document itValidatorsDoc = null;
    try {
        itValidatorsDoc = XMLUtilities.readFromFile("resources/validators/itValidators.xml");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (itPlannersDoc != null) {
        itValidators = itValidatorsDoc.getRootElement();
    }

    try {
        String appearence = itSettings.getChild("generalSettings").getChild("graphics")
                .getChildText("appearence");
        if (appearence.equals("Default")) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } else if (appearence.equals("Windows")) {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // Windows
        } else if (appearence.equals("Metal")) {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); // Metal
        } else if (appearence.equals("Motif")) {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); // Motif
        } else {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }

        // Need installation
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); // GTK+
        //UIManager.setLookAndFeel("javax.swing.plaf.mac.MacLookAndFeel"); // Mac

    } catch (Exception e) {
        //e.printStackTrace();
    }
    SplashScreen splash = new SplashScreen(5000);
    Thread t = new Thread(splash);
    t.start();
    ItSIMPLE.getInstance();

    WindowEventHandler closeWind = new WindowEventHandler();
    closeWind.itsimpleInst = instance;
    instance.addWindowListener(closeWind);
    instance.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    //instance = new ItSIMPLE();
    instance.setVisible(true);
    instance.setExtendedState(JFrame.MAXIMIZED_BOTH);
    //instance.repaint();
    //infoPanel.minimize();

}

From source file:com.iitb.cse.ConnectionInfo.java

public static synchronized void startlistenForClients(final Session session) {
    try {//from   w  w  w .ja va2  s .  c o  m

        if (session.connectionSocket != null) {
            stoplistenForClients(session);
            System.out.println("\nExisting Port closed");
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }
            startlistenForClients(session);
        }

        session.connectionSocket = new ServerSocket(Constants.ConnectionPORT);
        Constants.listenOnPort = true;
        while (true && acceptConnection) {
            System.out.println("\nListening for Client to Connect ......");
            final Socket sock = session.connectionSocket.accept();
            System.out.println("\nClient COnnected ......");
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    threadNo++;
                    ClientConnection.handleConnection(sock, session, threadNo);
                }
            };

            Thread t = new Thread(r);

            t.start();

        }
        System.out.println("\nStopping Listening!!!!!!!1");
    } catch (IOException ex) {
        try {
            if (session.connectionSocket != null) {
                stoplistenForClients(session);

            }
        } catch (Exception ex1) {
            System.out.println("\nException" + ex.toString() + "\n");
        }
    }
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

private static void closeOnNewThread(final Reader reader) {
    Thread thread = new Thread(new Runnable() {
        @Override/*from  ww  w  . j  a  v  a  2 s  .  c om*/
        public void run() {
            try {
                reader.close();
            } catch (Throwable ignore) {
            }
        }
    }, "closeInputStream");
    thread.setDaemon(true);
    thread.start();
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/*from w w  w. ja v  a  2s . c o  m*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

private static Thread redirect(InputStream in, OutputStream out) {
    Thread t = new Thread(new StreamRedirectTask(in, out));
    t.setDaemon(true);/*w w  w.  j  a v  a2s .c  om*/
    t.start();
    return t;
}