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.aos.protocol.http.httpcommon.ElementalHttpServer.java

public static void main(String... args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);/*ww w  . ja va 2  s.com*/
    }
    Thread t = new RequestListenerThread(8080, args[0]);
    t.setDaemon(false);
    t.start();
}

From source file:de.hadesrofl.mqtt_client.App.java

public static void main(String[] args) {
    String cf = "";
    if (args.length > 0) {
        cf = args[0];/*from  w  ww  .  j  a v a  2 s.  c om*/
    } else {
        cf = "config.json";
    }
    JSONObject config = JsonReader.readFile(cf);
    if (config == null)
        System.exit(-1);
    JSONObject broker = config.getJSONObject("broker");
    JSONObject topics = broker.getJSONObject("topics");
    Database db = null;
    try {
        JSONObject database = config.getJSONObject("database");
        db = new Database(database.getString("dbHost"), database.getString("dbPort"),
                database.getString("dbName"), database.getString("dbUser"), database.getString("dbPass"));
    } catch (JSONException e) {
        System.err.println("No database mentioned in config file");
    }
    List<ClientMqtt> clients = new ArrayList<ClientMqtt>();
    List<Thread> clientThreads = new ArrayList<Thread>();
    for (String topic : topics.keySet()) {
        ClientMqtt client = null;
        if (db == null) {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"),
                    topics.getString(topic));
        } else {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"), topics.getString(topic),
                    db);
        }
        Thread clientThread = new Thread(client);
        client.setSubscriber(broker.getBoolean("subscribe"));
        clients.add(client);
        clientThreads.add(clientThread);
        clientThread.start();
        // Need to wait a bit as the client needs to connect first
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.err.println("Thread can't sleep, need to take painkillers");
        }
        client.publishMessage("Ground control to Major Tom", 1);
    }
}

From source file:org.jfree.chart.demo.LegendManiaDemo.java

/**
 * Starting point for the demonstration application.
 * /* w  w  w . j ava 2s .c  o  m*/
 * @param args
 *           ignored.
 */
public static void main(final String[] args) {
    final LegendManiaDemo demo = new LegendManiaDemo(CHART_TITLE);
    demo.pack();
    demo.setSize(800, 600);
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);

    final Thread updater = demo.new UpdaterThread();
    updater.setDaemon(true);
    updater.start();
}

From source file:com.nohowdezign.gcpmanager.Main.java

public final static void main(String[] args) {
    //Remove old log, it does not need to be there anymore.
    File oldLog = new File("./CloudPrintManager.log");

    if (oldLog.exists()) {
        oldLog.delete();/*from w ww .jav  a 2s  .co  m*/
    }

    //Create a file reader for the props file
    Reader propsStream = null;
    try {
        propsStream = new FileReader("./props.json");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    PrintManagerProperties props = null;
    if (propsStream != null) {
        props = gson.fromJson(propsStream, PrintManagerProperties.class);
    } else {
        logger.error("Property file does not exist. Please create one.");
    }

    //Set the variables to what is in the props file
    String email = props.getEmail();
    String password = props.getPassword();
    String printerId = props.getPrinterId();
    amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob();
    timeRestraintsForPrinter = props.getTimeRestraintsForPrinter();

    JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays();

    //AuthenticationManager authenticationManager = new AuthenticationManager();
    //authenticationManager.setPasswordToUse(props.getAdministrativePassword());
    //authenticationManager.initialize(1337); //Start the authentication manager on port 1337

    try {
        cloudPrint.connect(email, password, "cloudprintmanager-1.0");
    } catch (CloudPrintAuthenticationException e) {
        logger.error(e.getMessage());
    }

    //TODO: Get a working website ready
    //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer");
    //adminConsole.start();

    Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager");
    printJobManager.start();

    try {
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            logger.error("Your operating system is not supported. Please switch to linux ya noob.");
            System.exit(1);
        } else {
            PrinterManager printerManager = new PrinterManager(cloudPrint);

            File cupsPrinterDir = new File("/etc/cups/ppd");

            if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) {
                for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) {
                    //Init all of the CUPS printers in the manager
                    printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName());
                }
            } else {
                logger.error("Please run this with a higher access level.");
                System.exit(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            getPrintingJobs(printerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.berkeley.sparrow.examples.BBackend.java

public static void main(String[] args) throws IOException, TException {
    ipAddress = InetAddress.getLocalHost().toString();
    OptionParser parser = new OptionParser();
    parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
    parser.accepts("help", "print help statement");
    OptionSet options = parser.parse(args);

    if (options.has("help")) {
        parser.printHelpOn(System.out);
        System.exit(-1);//from   ww  w  .  j a v a 2  s. c  o m
    }

    // Logger configuration: log to the console
    BasicConfigurator.configure();

    Configuration conf = new PropertiesConfiguration();

    if (options.has("c")) {
        String configFile = (String) options.valueOf("c");
        try {
            conf = new PropertiesConfiguration(configFile);
        } catch (ConfigurationException e) {
        }
    }
    // Start backend server
    LOG.setLevel(Level.toLevel(conf.getString(LOG_LEVEL, DEFAULT_LOG_LEVEL)));
    LOG.debug("debug logging on");
    int listenPort = conf.getInt(LISTEN_PORT, DEFAULT_LISTEN_PORT);
    int nodeMonitorPort = conf.getInt(NODE_MONITOR_PORT, NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT);
    batchingDelay = conf.getLong(BATCHING_DELAY, DEFAULT_BATCHING_DELAY);
    String nodeMonitorHost = conf.getString(NODE_MONITOR_HOST, DEFAULT_NODE_MONITOR_HOST);
    int workerThread = conf.getInt(WORKER_THREADS, DEFAULT_WORKER_THREADS);
    appClientAdress = InetAddress.getByName(conf.getString(APP_CLIENT_IP));
    appClientPortNumber = conf.getInt(APP_CLIENT_PORT_NUMBER, DEFAULT_APP_CLIENT_PORT_NUMBER);
    executor = Executors.newFixedThreadPool(workerThread);
    // Starting logging of results
    resultLog = new SynchronizedWrite("ResultsBackend.txt");
    Thread resultLogTh = new Thread(resultLog);
    resultLogTh.start();

    BBackend protoBackend = new BBackend();
    BackendService.Processor<BackendService.Iface> processor = new BackendService.Processor<BackendService.Iface>(
            protoBackend);

    TServers.launchSingleThreadThriftServer(listenPort, processor);
    protoBackend.initialize(listenPort, nodeMonitorHost, nodeMonitorPort);

}

From source file:com.autodomum.example.Example1.java

public static void main(String[] args) throws Exception {
    final ConfigurableApplicationContext context = SpringApplication.run(Example1.class, args);
    final JsonLampDao jsonLampDao = context.getBean(JsonLampDao.class);
    final EventComponent eventComponent = context.getBean(EventComponent.class);
    final EventContext eventContext = context.getBean(EventContext.class);
    final TelldusComponent telldusComponent = context.getBean(TelldusComponent.class);
    final NashornScriptComponent nashornScriptComponent = context.getBean(NashornScriptComponent.class);

    final Thread eventComponentThread = new Thread(eventComponent);
    eventComponentThread.setDaemon(true);
    eventComponentThread.setPriority(Thread.MIN_PRIORITY);
    eventComponentThread.setName("EventComponent");
    eventComponentThread.start();

    // Coordinates of Stockholm
    eventContext.setCoordinate(new Coordinate(18.063240d, 59.334591d));

    eventComponent.updateEventContext();
    eventComponent.register(LampStateChangedEvent.class, telldusComponent);

    final Thread telldusComponentThread = new Thread(telldusComponent);
    telldusComponentThread.setDaemon(true);
    telldusComponentThread.setPriority(Thread.MIN_PRIORITY);
    telldusComponentThread.setName("Telldus");
    telldusComponentThread.start();/*from w ww .ja va 2  s  .c  o m*/

    try (InputStream inputStream = Example1.class.getResourceAsStream("/lamps.json")) {
        jsonLampDao.load(inputStream);
    }

    try (InputStream inputStream = Example1.class.getResourceAsStream("/ai.js")) {
        nashornScriptComponent.replaceScript(inputStream);
    }
}

From source file:net.minder.httpcap.HttpCap.java

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure(ClassLoader.getSystemResourceAsStream("log4j.properties"));

    int port = DEFAULT_PORT;

    if (args.length > 0) {
        try {//from  w ww .  j av a  2  s  . c  om
            port = Integer.parseInt(args[0]);
        } catch (NumberFormatException nfe) {
            port = DEFAULT_PORT;
        }
    }

    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("HttpCap/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpCapHandler());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    //    if (port == 8443) {
    //      // Initialize SSL context
    //      ClassLoader cl = HttpCap.class.getClassLoader();
    //      URL url = cl.getResource("my.keystore");
    //      if (url == null) {
    //        System.out.println("Keystore not found");
    //        System.exit(1);
    //      }
    //      KeyStore keystore  = KeyStore.getInstance("jks");
    //      keystore.load(url.openStream(), "secret".toCharArray());
    //      KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
    //          KeyManagerFactory.getDefaultAlgorithm());
    //      kmfactory.init(keystore, "secret".toCharArray());
    //      KeyManager[] keymanagers = kmfactory.getKeyManagers();
    //      SSLContext sslcontext = SSLContext.getInstance("TLS");
    //      sslcontext.init(keymanagers, null, null);
    //      sf = sslcontext.getServerSocketFactory();
    //    }

    Thread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();
}

From source file:Main.java

public static void main(String... s) {
    cdl = new CountDownLatch(1);
    Thread a = new Thread(() -> {
        System.out.println("started a");
        try {/*from w w  w  .  j a  va  2  s  .c  om*/
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        cdl.countDown();
        System.out.println("stoped a");
    });
    Thread b = new Thread(() -> {
        System.out.println("started b");
        System.out.println("wait a");
        try {
            cdl.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("stoped b");
    });
    b.start();
    a.start();
}

From source file:com.adhi.webserver.WebServer.java

public static void main(String[] args) throws Exception {

    int port = 9999;

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*www . ja va 2  s. co m*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new MessageCommandHandler());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = WebServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    Thread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();
}

From source file:com.vikram.kdtree.ElementalHttpServer.java

public static void main(String[] args) throws Exception {
    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from  www.  ja  v a 2 s.  co m*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpPostReceiver());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    Properties properties = new Properties();
    properties.load(new FileInputStream("Config.properties"));

    Thread t = new RequestListenerThread(Integer.valueOf(properties.getProperty("requestPort")), httpService,
            null);
    t.setDaemon(false);
    t.start();
}