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:io.ingenieux.lambda.shell.LambdaShell.java

private static void runCommandArray(OutputStream os, String... args) throws Exception {
    PrintWriter pw = new PrintWriter(os, true);

    File tempPath = File.createTempFile("tmp-", ".sh");

    IOUtils.write(StringUtils.join(args, " "), new FileOutputStream(tempPath));

    List<String> processArgs = new ArrayList<>(Arrays.asList("/bin/bash", "-x", tempPath.getAbsolutePath()));

    ProcessBuilder psBuilder = new ProcessBuilder(processArgs).//
            redirectErrorStream(true);//

    final Process process = psBuilder.start();

    final Thread t = new Thread(() -> {
        try {/*from  w  w w .  j a v  a  2s. c o m*/
            IOUtils.copy(process.getInputStream(), os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    t.start();

    process.waitFor();

    t.join();

    int resultCode = process.exitValue();
}

From source file:cam.cl.kilo.RESTBarcode.java

/**
 * Make different API calls according to the item's type
 *
 * @param barcodeNo The item's barcode number
 * @param barcodeType The type of the barcode (ISBN, UPC or other)
 * @return ItemInfo object with item information
 *//*  w w  w.  j a  v  a  2s.c om*/
public static ItemInfo populateItemInfo(String barcodeNo, String barcodeType) {
    ItemInfo info = new ItemInfo();

    Thread tAmzn = new Thread(new AmznItemLookup(barcodeNo, barcodeType, info));
    Thread tGR = new Thread(new GoodReadsLookup(barcodeNo, barcodeType, info));

    tAmzn.start();

    if ("ISBN".equals(barcodeType))
        tGR.start();

    while (tAmzn.isAlive() || tGR.isAlive())
        ;

    if (!"ISBN".equals(barcodeType)) {
        Thread tOMDB = new Thread(new OMDBLookup(barcodeNo, barcodeType, info));
        while (tOMDB.isAlive())
            ;
    }

    return info;
}

From source file:com.zergiu.tvman.TVMan.java

private static void startServer(final TVManWebServer server) {
    Thread startupThread = new Thread(new Runnable() {
        @Override/*www  . j ava2 s  .c o m*/
        public void run() {
            try {
                server.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    startupThread.start();
}

From source file:com.modeln.build.common.tool.CMnCmdLineTool.java

/**
 * Wait for the executing process to complete.
 *
 * @param  process  Process to monitor//  w ww. j  a va 2 s  .  c o  m
 * @param  profile  Enable or disable execution profiling
 */
public static int wait(Process process, boolean profile) throws InterruptedException {
    Date startDate = null;
    if (profile) {
        startDate = new Date();
    }

    // Use a separate thread to relay the process output to the user
    CMnProcessOutput stdout = new CMnProcessOutput(process, process.getInputStream());
    CMnProcessOutput stderr = new CMnProcessOutput(process, process.getErrorStream());
    Thread out = new Thread(stdout);
    Thread err = new Thread(stderr);
    out.start();
    err.start();

    // Wait for the process to complete
    int result = process.waitFor();

    // Display the elapsed time for this operation
    if (profile) {
        displayElapsedTime(startDate, new Date(), "Execution complete: ");
    }

    return result;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void removeAllCookiesV21() {
    final CookieManager cookieManager = CookieManager.getInstance();

    Looper looper = Looper.myLooper();//from w w w .j a  v a2  s  .c  om
    boolean prepared = false;
    if (looper == null) {
        Looper.prepare();
        prepared = true;
    }

    // requires a looper
    cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
        @Override
        public void onReceiveValue(Boolean value) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    // is synchronous, run in background
                    cookieManager.flush();
                }
            };
            thread.start();
        }
    });

    if (prepared) {
        looper = Looper.myLooper();
        if (looper != null) {
            looper.quit();
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.InterceptorsTest.java

/**
 * Runs interceptions test scenario.//from   w w  w. j  a  v  a 2 s  .  com
 *
 * @throws Exception
 *             if exception occurs while running interceptions test
 */
public static void interceptionsTest() throws Exception {
    String tnt4jCfgPath = System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY);
    if (StringUtils.isEmpty(tnt4jCfgPath)) {
        URL defaultCfg = InterceptionsManager.getDefaultTrackerConfiguration();
        System.setProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY, defaultCfg.toExternalForm());
    }

    final Consumer<String, String> consumer = initConsumer();

    Thread pt = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                produce();
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });

    Thread ct = new Thread(new Runnable() {
        @Override
        public void run() {
            consume(consumer);
        }
    });
    ct.start();

    pt.start();
    pt.join();
    consumer.wakeup();
    ct.join();
}

From source file:com.splout.db.benchmark.TCPTest.java

public static void tcpTest(String file, String table)
        throws UnknownHostException, IOException, InterruptedException, JSONSerDeException {
    final TCPServer server = new TCPServer(8888, file, table);

    Thread t = new Thread() {
        @Override/*  w ww  .j a v  a2s  . c om*/
        public void run() {
            server.serve();
        }
    };
    t.start();

    while (!server.isServing()) {
        Thread.sleep(100);
    }

    Socket clientSocket = new Socket("localhost", 8888);
    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));

    try {
        do {
            // Read a record
            inFromServer.readUTF();
            inFromServer.readInt();
            inFromServer.readDouble();
            inFromServer.readUTF();
        } while (true);
    } catch (Throwable th) {
        th.printStackTrace();
    }

    clientSocket.close();
    server.stop();
    t.interrupt();
}

From source file:io.trivium.Central.java

public static void start() {

    //register activities
    Registry.INSTANCE.reload();//from w ww  .  ja  v  a  2  s . com

    try {
        //init ui handler
        Binding b = Registry.INSTANCE.getBinding(TypeRef.getInstance(WebUI.class.getCanonicalName()));
        b.startBinding();
        //init web object handler
        b = Registry.INSTANCE.getBinding(TypeRef.getInstance(WebObjectHandler.class.getCanonicalName()));
        b.startBinding();
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "error initializing the builtin http handler", ex);
    }
    //start anystore server
    Thread td = new Thread(AnyServer.INSTANCE, "anystore");
    td.setDaemon(true);
    td.start();

    // init profiler
    Timer t = new Timer();
    //one second after next time frame starts
    long start = TimeUtils.getTimeFrameStart(new Date().getTime() + 60000);
    t.schedule(Profiler.INSTANCE, new Date(start), 60000);

    logger.log(Level.INFO,
            "trivium is now running and accessible through the web interface on http://localhost:12345/ui/");
}

From source file:org.carewebframework.api.thread.ThreadUtil.java

/**
 * Starts a thread. If an executor service is available, that is used. Otherwise, the thread's
 * start method is called./*from   w  w w. ja v a 2  s .  co m*/
 * 
 * @param thread Thread to start.
 */
public static void startThread(Thread thread) {
    if (log.isDebugEnabled()) {
        log.debug("Starting background thread: " + thread);
    }

    ExecutorService executor = getTaskExecutor();

    if (executor != null) {
        executor.execute(thread);
    } else {
        thread.start();
    }
}

From source file:com.ec2box.manage.util.SSHUtil.java

/**
 * open new ssh session on host system// w  w  w  . j a  v a  2s.c  o  m
 *
 * @param passphrase     key passphrase for instance
 * @param password       password for instance
 * @param userId         user id
 * @param sessionId      session id
 * @param hostSystem     host system
 * @param userSessionMap user session map
 * @return status of systems
 */
public static HostSystem openSSHTermOnSystem(String passphrase, String password, Long userId, Long sessionId,
        HostSystem hostSystem, Map<Long, UserSchSessions> userSessionMap) {

    JSch jsch = new JSch();

    int instanceId = getNextInstanceId(sessionId, userSessionMap);
    hostSystem.setStatusCd(HostSystem.SUCCESS_STATUS);
    hostSystem.setInstanceId(instanceId);

    SchSession schSession = null;

    try {
        EC2Key ec2Key = EC2KeyDB.getEC2Key(hostSystem.getKeyId());
        //add private key
        if (ec2Key != null && ec2Key.getId() != null) {
            if (passphrase != null && !passphrase.trim().equals("")) {
                jsch.addIdentity(ec2Key.getId().toString(), ec2Key.getPrivateKey().trim().getBytes(), null,
                        passphrase.getBytes());
            } else {
                jsch.addIdentity(ec2Key.getId().toString(), ec2Key.getPrivateKey().trim().getBytes(), null,
                        null);
            }
        }

        //create session
        Session session = jsch.getSession(hostSystem.getUser(), hostSystem.getHost(), hostSystem.getPort());

        //set password if it exists
        if (password != null && !password.trim().equals("")) {
            session.setPassword(password);
        }
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setServerAliveInterval(SERVER_ALIVE_INTERVAL);
        session.connect(SESSION_TIMEOUT);
        Channel channel = session.openChannel("shell");
        if ("true".equals(AppConfig.getProperty("agentForwarding"))) {
            ((ChannelShell) channel).setAgentForwarding(true);
        }
        ((ChannelShell) channel).setPtyType("xterm");

        InputStream outFromChannel = channel.getInputStream();

        //new session output
        //new session output
        SessionOutput sessionOutput = new SessionOutput(sessionId, hostSystem);

        Runnable run = new SecureShellTask(sessionOutput, outFromChannel);
        Thread thread = new Thread(run);
        thread.start();

        OutputStream inputToChannel = channel.getOutputStream();
        PrintStream commander = new PrintStream(inputToChannel, true);

        channel.connect();

        schSession = new SchSession();
        schSession.setUserId(userId);
        schSession.setSession(session);
        schSession.setChannel(channel);
        schSession.setCommander(commander);
        schSession.setInputToChannel(inputToChannel);
        schSession.setOutFromChannel(outFromChannel);
        schSession.setHostSystem(hostSystem);

    } catch (Exception e) {
        hostSystem.setErrorMsg(e.getMessage());
        if (e.getMessage().toLowerCase().contains("userauth fail")) {
            hostSystem.setStatusCd(HostSystem.PUBLIC_KEY_FAIL_STATUS);
        } else if (e.getMessage().toLowerCase().contains("auth fail")
                || e.getMessage().toLowerCase().contains("auth cancel")) {
            hostSystem.setStatusCd(HostSystem.AUTH_FAIL_STATUS);
        } else if (e.getMessage().toLowerCase().contains("unknownhostexception")) {
            hostSystem.setErrorMsg("DNS Lookup Failed");
            hostSystem.setStatusCd(HostSystem.HOST_FAIL_STATUS);
        } else {
            hostSystem.setStatusCd(HostSystem.GENERIC_FAIL_STATUS);
        }
    }

    //add session to map
    if (hostSystem.getStatusCd().equals(HostSystem.SUCCESS_STATUS)) {
        //get the server maps for user
        UserSchSessions userSchSessions = userSessionMap.get(sessionId);

        //if no user session create a new one
        if (userSchSessions == null) {
            userSchSessions = new UserSchSessions();
        }
        Map<Integer, SchSession> schSessionMap = userSchSessions.getSchSessionMap();

        //add server information
        schSessionMap.put(instanceId, schSession);
        userSchSessions.setSchSessionMap(schSessionMap);
        //add back to map
        userSessionMap.put(sessionId, userSchSessions);
    }

    SystemStatusDB.updateSystemStatus(hostSystem, userId);
    SystemDB.updateSystem(hostSystem);

    return hostSystem;
}