Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

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

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

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

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 268");
    shell.setLayout(new FillLayout());
    StyledText styledText = new StyledText(shell, SWT.V_SCROLL);
    String multiLineString = "";
    for (int i = 0; i < 200; i++) {
        multiLineString = multiLineString.concat("This is line number " + i + " in the multi-line string.\n");
    }/*ww w.  j  a v  a2 s  . c om*/
    styledText.setText(multiLineString);
    shell.setSize(styledText.computeSize(SWT.DEFAULT, 400));
    shell.open();
    // move cursor over styled text
    Rectangle clientArea = shell.getClientArea();
    Point location = shell.getLocation();
    Event event = new Event();
    event.type = SWT.MouseMove;
    event.x = location.x + clientArea.width / 2;
    event.y = location.y + clientArea.height / 2;
    display.post(event);
    styledText.addListener(SWT.MouseWheel, e -> System.out.println("Mouse Wheel event " + e));
    new Thread() {
        Event event;

        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                event = new Event();
                event.type = SWT.MouseWheel;
                event.detail = SWT.SCROLL_LINE;
                event.count = -2;
                if (!display.isDisposed())
                    display.post(event);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    }.start();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

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

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 151");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        item.setText("Item " + data[index]);
    });/*from  w w  w .  jav a 2  s . c  om*/
    Thread thread = new Thread() {
        @Override
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(() -> {
                    if (table.isDisposed())
                        return;
                    table.setItemCount(data.length);
                    table.clearAll();
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:ai.emot.demo.EmotAIDemo.java

public static void main(String[] args) throws IOException, InterruptedException {
    if (args.length != 2) {
        printUsage();//from  w  w w  .  j a va  2s .c o m
        System.exit(0);
    }

    String emotAIAPIBaseUrl = args[0];
    String accessToken = args[1];

    PathMatchingResourcePatternResolver fileResolver = new PathMatchingResourcePatternResolver(
            EmotAIDemo.class.getClassLoader());
    Resource[] resources = fileResolver.getResources("images");
    File dir = resources[0].getFile();
    File imagesDir = new File(dir, "/face/cropped");

    EmotAI emotAI = new EmotAITemplate(emotAIAPIBaseUrl, accessToken);

    // Create a display for the images
    ImageDisplay<Long> imageDisplay = new ImageDisplay<Long>(250, 250);

    for (File imageFile : imagesDir.listFiles(new JpegFileFilter())) {
        // Read each image
        BufferedImage image = ImageIO.read(imageFile);

        // Get the emotion profile for each image
        EmotionProfile emotionProfile = emotAI.emotionOperations().getFaceImageEmotionProfile(image);

        // Output emotion, and display image
        System.out.println(imageFile.getName() + " : " + emotionProfile);
        imageDisplay.onFrameUpdate(new SerializableBufferedImageAdapter(image), 1l);

        // Sleep for 1 second
        Thread.sleep(1000);

    }

    System.exit(1);
}

From source file:example.springdata.redis.sentinel.RedisSentinelApplication.java

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

    ApplicationContext context = SpringApplication.run(RedisSentinelApplication.class, args);

    StringRedisTemplate template = context.getBean(StringRedisTemplate.class);
    template.opsForValue().set("loop-forever", "0");

    StopWatch stopWatch = new StopWatch();

    while (true) {

        try {/*from   w  ww  . j a v  a  2 s. c om*/

            String value = "IT:= " + template.opsForValue().increment("loop-forever", 1);
            printBackFromErrorStateInfoIfStopWatchIsRunning(stopWatch);
            System.out.println(value);

        } catch (RuntimeException e) {

            System.err.println(e.getCause().getMessage());
            startStopWatchIfNotRunning(stopWatch);
        }

        Thread.sleep(1000);
    }
}

From source file:com.vaushell.superpipes.App.java

/**
 * Main method.//w  w  w. ja  v  a 2  s  . co  m
 *
 * @param args Command line arguments
 * @throws Exception
 */
public static void main(final String... args) throws Exception {
    // My config
    final XMLConfiguration config = new XMLConfiguration();
    config.setDelimiterParsingDisabled(true);

    final long delay;
    final Path datas;
    switch (args.length) {
    case 1: {
        config.load(args[0]);
        datas = Paths.get("datas");
        delay = 10000L;

        break;
    }

    case 2: {
        config.load(args[0]);
        datas = Paths.get(args[1]);
        delay = 10000L;

        break;
    }

    case 3: {
        config.load(args[0]);
        datas = Paths.get(args[1]);
        delay = Long.parseLong(args[2]);

        break;
    }

    default: {
        config.load("conf/configuration.xml");
        datas = Paths.get("datas");
        delay = 10000L;

        break;
    }
    }

    final Dispatcher dispatcher = new Dispatcher();
    dispatcher.init(config, datas, new VC_SystemInputFactory());

    // Run
    dispatcher.start();

    // Wait
    try {
        Thread.sleep(delay);
    } catch (final InterruptedException ex) {
        // Ignore
    }

    // Stop
    dispatcher.stopAndWait();
}

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args/*w ww  .ja  v a2s  .co m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}

From source file:com.damon.rocketmq.example.operation.Producer.java

public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();//from  w  w w . j  a  v  a 2s.co m

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(topic, tags, keys,
                        ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%-8d %s%n", i, sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}

From source file:Snippet104.java

public static void main(String[] args) {
    final Display display = new Display();
    final int[] count = new int[] { 4 };
    final Image image = new Image(display, 300, 300);
    final Shell splash = new Shell(SWT.ON_TOP);
    final ProgressBar bar = new ProgressBar(splash, SWT.NONE);
    bar.setMaximum(count[0]);//from   www .j  av a 2  s. co  m
    Label label = new Label(splash, SWT.NONE);
    label.setImage(image);
    FormLayout layout = new FormLayout();
    splash.setLayout(layout);
    FormData labelData = new FormData();
    labelData.right = new FormAttachment(100, 0);
    labelData.bottom = new FormAttachment(100, 0);
    label.setLayoutData(labelData);
    FormData progressData = new FormData();
    progressData.left = new FormAttachment(0, 5);
    progressData.right = new FormAttachment(100, -5);
    progressData.bottom = new FormAttachment(100, -5);
    bar.setLayoutData(progressData);
    splash.pack();
    Rectangle splashRect = splash.getBounds();
    Rectangle displayRect = display.getBounds();
    int x = (displayRect.width - splashRect.width) / 2;
    int y = (displayRect.height - splashRect.height) / 2;
    splash.setLocation(x, y);
    splash.open();
    display.asyncExec(new Runnable() {
        public void run() {
            Shell[] shells = new Shell[count[0]];
            for (int i = 0; i < count[0]; i++) {
                shells[i] = new Shell(display);
                shells[i].setSize(300, 300);
                shells[i].addListener(SWT.Close, new Listener() {
                    public void handleEvent(Event e) {
                        --count[0];
                    }
                });
                bar.setSelection(i + 1);
                try {
                    Thread.sleep(1000);
                } catch (Throwable e) {
                }
            }
            splash.close();
            image.dispose();
            for (int i = 0; i < count[0]; i++) {
                shells[i].open();
            }
        }
    });
    while (count[0] != 0) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:edu.stanford.junction.simulator.simThread.java

public static void main(String[] argv) {
    for (int i = 0; i < NumOfActivity; i++) {
        simThread st = new simThread(NumOfMessage, NumOfParticipant, i);
        st.start();//from   w  ww .  j a  v  a  2  s .  co  m
    }
    while (true) {
        try {
            Thread.sleep(500000);
        } catch (Exception e) {
        }
    }
}

From source file:com.nubits.nubot.tests.TestRPC.java

public static void main(String[] args) {

    //Default values
    String custodian = Passwords.CUSTODIAN_PUBLIC_ADDRESS;
    String user = Passwords.NUD_RPC_USER;
    String pass = Passwords.NUD_RPC_PASS;
    double sell = 0;
    double buy = 0;
    //java -jar testRPC user pass custodian sell buy
    if (args.length == 5) {
        LOG.info("Reading input parameters");
        user = args[0];/* ww  w .  jav a  2s.  com*/
        pass = args[1];
        custodian = args[2];
        sell = Double.parseDouble(args[3]);
        buy = Double.parseDouble(args[4]);
    }

    Utils.loadProperties("settings.properties");

    TestRPC test = new TestRPC();

    test.setup(Constant.INTERNAL_EXCHANGE_PEATIO, custodian, Constant.NBT_BTC, user, pass);
    test.testCheckNudTask();
    try {
        Thread.sleep(2000);

    } catch (InterruptedException ex) {
        Logger.getLogger(TestRPC.class.getName()).log(Level.SEVERE, null, ex);
    }
    //test.testGetInfo();
    //test.testIsConnected();
    test.testSendLiquidityInfo(buy, sell, 1);
    //test.testGetLiquidityInfo();
    //test.testGetLiquidityInfo(Constant.SELL, Passwords.CUSTODIA_PUBLIC_ADDRESS);
    //test.testGetLiquidityInfo(Constant.BUY, Passwords.CUSTODIA_PUBLIC_ADDRESS);

    System.exit(0);

}