Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

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

Prototype

public Thread(String name) 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    float sampleRate = 8000;
    int sampleSizeInBits = 8;
    int channels = 1;
    boolean signed = true;
    boolean bigEndian = true;
    final AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);/*from  w  w  w  . j av a  2 s.  c  om*/
    line.start();
    Runnable runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {

                int count = line.read(buffer, 0, buffer.length);
                if (count > 0) {
                    out.write(buffer, 0, count);
                }

                out.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-1);
            }
        }
    };
    Thread captureThread = new Thread(runner);
    captureThread.start();

    byte audio[] = out.toByteArray();
    InputStream input = new ByteArrayInputStream(audio);
    final SourceDataLine line1 = (SourceDataLine) AudioSystem.getLine(info);
    final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
    line1.open(format);
    line1.start();

    runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {
                int count;
                while ((count = ais.read(buffer, 0, buffer.length)) != -1) {
                    if (count > 0) {
                        line1.write(buffer, 0, count);
                    }
                }
                line1.drain();
                line1.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-3);
            }
        }
    };
    Thread playThread = new Thread(runner);
    playThread.start();

}

From source file:ThreadDemo.java

/**
 * This main method creates and starts two threads in addition to the initial
 * thread that the interpreter creates to invoke the main() method.
 *//*from  ww  w  . ja  v a  2 s . c  o m*/
public static void main(String[] args) {
    // Create the first thread: an instance of this class. Its body is
    // the run() method above
    ThreadDemo thread1 = new ThreadDemo();

    // Create the second thread by passing a Runnable object to the
    // Thread() construtor. The body of this thread is the run() method
    // of the anonymous Runnable object below.
    Thread thread2 = new Thread(new Runnable() {
        public void run() {
            for (int i = 0; i < 5; i++)
                compute();
        }
    });

    // Set the priorities of these two threads, if any are specified
    if (args.length >= 1)
        thread1.setPriority(Integer.parseInt(args[0]));
    if (args.length >= 2)
        thread2.setPriority(Integer.parseInt(args[1]));

    // Start the two threads running
    thread1.start();
    thread2.start();

    // This main() method is run by the initial thread created by the
    // Java interpreter. Now that thread does some stuff, too.
    for (int i = 0; i < 5; i++)
        compute();

    // We could wait for the threads to stop running with these lines
    // But they aren't necessary here, so we don't bother.
    // try {
    // thread1.join();
    // thread2.join();
    // } catch (InterruptedException e) {}

    // The Java VM exits only when the main() method returns, and when all
    // threads stop running (except for daemon threads--see setDaemon()).
}

From source file:ProducerConsumerExample.java

public static void main(String[] args) {
    BlockingQueue<String> drop = new SynchronousQueue<String>();
    (new Thread(new Producer(drop))).start();
    (new Thread(new Consumer(drop))).start();
}

From source file:com.taobao.tddl.common.DynamicLogTest.java

public static void main(String[] args) throws InterruptedException {
    MockServer.setUpMockServer();/* ww  w.j a v a 2  s .  c  om*/

    DynamicLog dynamicLog = DynamicLog.getInstance("test");
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 300; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                MockServer.setConfigInfo("com.taobao.tddl.v1_test_buryPoints", getSpringXmlString("test", //
                        i + "+ 'th:date='+(java.util.Date)args[0]"));
            }
        }
    }).start();

    for (int i = 0; i < 300; i++) {
        dynamicLog.warn("test", new Object[] { new Date() }, "defaultLog", log);
        Thread.sleep(1000);
    }

    MockServer.tearDownMockServer();
}

From source file:com.lucidtechnics.blackboard.examples.cocothemonkey.CocoTheMonkey.java

public static void main(String[] _args) throws Exception {
    try {//from  www.  j  av a 2s  .c o m
        final Blackboard blackboard = new Blackboard();

        logger.info("Starting Coco The Monkey");
        System.out.println("Starting Coco The Monkey");

        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-1-" + i);
                    Mango mango = new Mango("Coco-2-" + i);
                    Eagle eagle = new Eagle("Coco-3-" + i);
                    Hunter hunter = new Hunter("Coco-5-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-4-" + i);
                    Mango mango = new Mango("Coco-1-" + i);
                    Eagle eagle = new Eagle("Coco-5-" + i);
                    Hunter hunter = new Hunter("Coco-3-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-3-" + i);
                    Mango mango = new Mango("Coco-5-" + i);
                    Eagle eagle = new Eagle("Coco-4-" + i);
                    Hunter hunter = new Hunter("Coco-2-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread4 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-2-" + i);
                    Mango mango = new Mango("Coco-3-" + i);
                    Eagle eagle = new Eagle("Coco-1-" + i);
                    Hunter hunter = new Hunter("Coco-4-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        Thread thread5 = new Thread(new Runnable() {
            public void run() {
                synchronized (blackboard) {
                    try {
                        blackboard.wait();
                    } catch (InterruptedException e) {
                    }
                }

                for (int i = 0; i < 100; i++) {
                    Monkey monkey = new Monkey("Coco-5-" + i);
                    Mango mango = new Mango("Coco-4-" + i);
                    Eagle eagle = new Eagle("Coco-2-" + i);
                    Hunter hunter = new Hunter("Coco-1-" + i);

                    blackboard.placeOnBlackboard(eagle);
                    blackboard.placeOnBlackboard(mango);
                    blackboard.placeOnBlackboard(monkey);
                    blackboard.placeOnBlackboard(hunter);
                }
            }
        });

        thread1.start();
        thread2.start();

        thread3.start();
        thread4.start();
        thread5.start();

        try {
            Thread.currentThread().sleep(1000);
        } catch (Throwable t) {
        }

        synchronized (blackboard) {
            blackboard.notifyAll();
        }

        Object object = new Object();

        synchronized (object) {
            try {
                object.wait();
            } catch (InterruptedException e) {
            }
        }
    } finally {
    }
}

From source file:org.sourcepit.docker.watcher.Main.java

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

    final HttpClientFactory clientFactory = new HttpClientFactory() {
        @Override//  w  ww  . ja  v  a  2s. c om
        public CloseableHttpClient createHttpClient() {
            return HttpClients.createDefault();
        }
    };

    final String dockerDaemonUri = "http://192.168.56.101:2375";
    final String consulAgentUri = "http://192.168.56.101:8500";

    final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>();

    final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(),
            consulAgentUri);

    final Thread containerStateDispatcher = new Thread("Consul Forwarder") {
        @Override
        public void run() {
            while (true) {
                try {
                    consulForwarder.forward(queue.take());
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    LOG.error("Error while forwarding Docker container state to Consul.", e);
                }
            }
        }
    };
    containerStateDispatcher.start();

    final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) {
        @Override
        protected void handle(List<JsonObject> containerState) {
            queue.add(containerState);
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            watcher.stop();
            while (containerStateDispatcher.isAlive()) {
                containerStateDispatcher.interrupt();
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    watcher.start();
}

From source file:org.eclipse.swt.snippets.Snippet130.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 130");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    text.setLayoutData(new GridData(GridData.FILL_BOTH));
    final int[] nextId = new int[1];
    Button b = new Button(shell, SWT.PUSH);
    b.setText("invoke long running job");
    b.addSelectionListener(widgetSelectedAdapter(e -> {
        Runnable longJob = new Runnable() {
            boolean done = false;
            int id;

            @Override/* w  w w.  j ava 2s.c  o  m*/
            public void run() {
                Thread thread = new Thread(() -> {
                    id = nextId[0]++;
                    display.syncExec(() -> {
                        if (text.isDisposed())
                            return;
                        text.append("\nStart long running task " + id);
                    });
                    for (int i = 0; i < 100000; i++) {
                        if (display.isDisposed())
                            return;
                        System.out.println("do task that takes a long time in a separate thread " + id);
                    }
                    if (display.isDisposed())
                        return;
                    display.syncExec(() -> {
                        if (text.isDisposed())
                            return;
                        text.append("\nCompleted long running task " + id);
                    });
                    done = true;
                    display.wake();
                });
                thread.start();
                while (!done && !shell.isDisposed()) {
                    if (!display.readAndDispatch())
                        display.sleep();
                }
            }
        };
        BusyIndicator.showWhile(display, longJob);
    }));
    shell.setSize(250, 150);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.qubole.rubix.bookkeeper.BookKeeperServer.java

public static void main(String[] args) {
    conf = new Configuration();

    Runnable bookKeeperServer = new Runnable() {
        public void run() {
            startServer(conf);//from w ww .jav a2 s.  c om
        }
    };

    new Thread(bookKeeperServer).run();
}

From source file:com.eaio.uuid.UUIDPerformance.java

public static void main(String[] args) {

    Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors()];

    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread(new UUIDRunnable(count / threads.length));
    }// w  w  w.j a  v a 2 s. co m

    StopWatch watch = new StopWatch();
    watch.start();

    for (Thread t : threads) {
        t.start();
    }

    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException e) {
            // Moo
        }
    }

    watch.stop();
    System.out.println(watch.getTime());
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public static void main(String[] args) throws Exception {
    applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    new Thread(new LogInvoker(obterConfiguracaoWildfly(System.getProperty("jvm.host")))).start();
}