Example usage for java.lang Runnable run

List of usage examples for java.lang Runnable run

Introduction

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

Prototype

public abstract void run();

Source Link

Document

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Usage

From source file:persons.controller.Main.java

public static void main(String[] args) {
    AbstractApplicationContext ctx = new FileSystemXmlApplicationContext("beans.xml");
    Runnable test = (Runnable) ctx.getBean("test");
    test.run();
    ctx.close();/*w  w w  .j a  v  a 2 s .  c  o m*/
}

From source file:no.trank.openpipe.tutorial.intranet.Main.java

public static void main(String[] args) {
    if (args.length < 1) {
        usage();//from   www .  j a  v  a2s .  c om
    } else {
        try {
            ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                    "intranetApplicationContext.xml");
            try {
                FileDocumentReader directory = (FileDocumentReader) appContext.getBean("fileDocumentReader",
                        FileDocumentReader.class);
                directory.setDirectory(args[0]);

                if (args.length > 1) {
                    SolrHttpDocumentPoster solrDocumentPoster = (SolrHttpDocumentPoster) appContext
                            .getBean("solrDocumentPoster", SolrHttpDocumentPoster.class);
                    SolrDocumentProcessor solrDocumentProcessor = (SolrDocumentProcessor) appContext
                            .getBean("solrDocumentProcessor", SolrDocumentProcessor.class);

                    String solrUrl = args[1];
                    solrDocumentPoster.setPostUrl(solrUrl + "/update");
                    solrDocumentProcessor.setSolrSchemaUrl(solrUrl + "/admin/get-file.jsp?file=schema.xml");
                }

                Runnable pipelineApplication = (Runnable) appContext.getBean("pipelineApplicationBean",
                        Runnable.class);
                pipelineApplication.run();
            } finally {
                appContext.close();
            }
        } catch (BeansException e) {
            log.error("Spring error", e);
        }
    }
}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);/*from  www  .  j a v  a2 s  .  co  m*/

    File baseDir = new File("/Users/kameshs/git/fabric8io/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

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

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

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

}

From source file:io.reactiverse.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);// ww  w  .  ja  v a  2  s  .c om

    File baseDir = new File("/Users/kameshs/git/reactiverse/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

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

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

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

}

From source file:Main.java

public static void main(String[] arg) throws Exception {
    Runnable parallelCode = () -> {
        HashSet<String> allThreads = new HashSet<>();
        IntStream.range(0, 1_000_000).parallel().filter(i -> {
            allThreads.add(Thread.currentThread().getName());
            return false;
        }).min();//from  w w  w.j  a v  a 2  s  . c o m
        System.out.println("executed by " + allThreads);
    };
    System.out.println("default behavior: ");
    parallelCode.run();
    System.out.println("specialized pool:");
    ForkJoinPool pool = new ForkJoinPool(2);
    pool.submit(parallelCode).get();
}

From source file:net.darkmist.alib.spring.Main.java

public static void main(String[] args) {
    FileSystemXmlApplicationContext ctx;
    Runnable mb;
    boolean doExit = false;
    int exitCode = 0;

    if (args.length < 1)
        usage();/*from   w  w  w .  j a  va2s.  co m*/
    ctx = new FileSystemXmlApplicationContext(args[0]);
    mb = (Runnable) ctx.getBean(MAIN_BEAN);
    if (mb instanceof MainBean)
        ((MainBean) mb).setArgs(args, 1, args.length - 1);
    else if (args.length > 1)
        throw new IllegalArgumentException("main bean does not take arguments");
    mb.run();
    if (mb instanceof MainBean) {
        exitCode = ((MainBean) mb).getExitCode();
        doExit = true;
    }
    mb = null;
    ctx.close();
    if (doExit)
        System.exit(exitCode);
}

From source file:JDAC.JDAC.java

public static void main(String[] args) {
    try {/*from  w w w.j av a  2 s . c o m*/
        UIManager.setLookAndFeel(
                //UIManager.getSystemLookAndFeelClassName());
                UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(new Frame(), "" + "Something strange happened\n"
                + "If the error persists please contact the system administrator\n" + "ERR: theme error");
    }

    JDAC demo = new JDAC();

    RefineryUtilities.centerFrameOnScreen(demo);
    Runnable tmp = new Runnable() {
        public void run() {
            System.out.println("JDAC");
            System.out.println("Credits: Michele Lizzit - https://lizzit.it/jdac");

            searchForPorts();
        }
    };
    tmp.run();
}

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

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    Composite comp = new Composite(shell, SWT.NONE);
    comp.setLayout(new FillLayout());
    GLData data = new GLData();
    data.doubleBuffer = true;//  w  ww .j a  v  a 2s.co  m
    final GLCanvas canvas = new GLCanvas(comp, SWT.NONE, data);

    canvas.setCurrent();
    GL.createCapabilities();

    canvas.addListener(SWT.Resize, event -> {
        Rectangle bounds = canvas.getBounds();
        float fAspect = (float) bounds.width / (float) bounds.height;
        canvas.setCurrent();
        GL.createCapabilities();
        GL11.glViewport(0, 0, bounds.width, bounds.height);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        float near = 0.5f;
        float bottom = -near * (float) Math.tan(45.f / 2);
        float left = fAspect * bottom;
        GL11.glFrustum(left, -left, bottom, -bottom, near, 400.f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();
    });

    GL11.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    GL11.glColor3f(1.0f, 0.0f, 0.0f);
    GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
    GL11.glClearDepth(1.0);
    GL11.glLineWidth(2);
    GL11.glEnable(GL11.GL_DEPTH_TEST);

    shell.setText("SWT/LWJGL Example");
    shell.setSize(640, 480);
    shell.open();

    final Runnable run = new Runnable() {
        int rot = 0;

        @Override
        public void run() {
            if (!canvas.isDisposed()) {
                canvas.setCurrent();
                GL.createCapabilities();
                GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
                GL11.glClearColor(.3f, .5f, .8f, 1.0f);
                GL11.glLoadIdentity();
                GL11.glTranslatef(0.0f, 0.0f, -10.0f);
                float frot = rot;
                GL11.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);
                GL11.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);
                rot++;
                GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
                GL11.glColor3f(0.9f, 0.9f, 0.9f);
                drawTorus(1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15);
                canvas.swapBuffers();
                display.asyncExec(this);
            }
        }
    };
    canvas.addListener(SWT.Paint, event -> run.run());
    display.asyncExec(run);

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:example.Listener.java

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

    String user = env("ACTIVEMQ_USER", "admin");
    String password = env("ACTIVEMQ_PASSWORD", "password");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "1883"));
    final String destination = arg(args, 0, "/topic/event");

    MQTT mqtt = new MQTT();
    mqtt.setHost(host, port);/*  w ww .  j a  v  a 2  s  .  c o m*/
    mqtt.setUserName(user);
    mqtt.setPassword(password);

    final CallbackConnection connection = mqtt.callbackConnection();
    connection.listener(new org.fusesource.mqtt.client.Listener() {
        long count = 0;
        long start = System.currentTimeMillis();

        public void onConnected() {
        }

        public void onDisconnected() {
        }

        public void onFailure(Throwable value) {
            value.printStackTrace();
            System.exit(-2);
        }

        public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
            String body = msg.utf8().toString();
            if ("SHUTDOWN".equals(body)) {
                long diff = System.currentTimeMillis() - start;
                System.out.println(String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0)));
                connection.disconnect(new Callback<Void>() {
                    @Override
                    public void onSuccess(Void value) {
                        System.exit(0);
                    }

                    @Override
                    public void onFailure(Throwable value) {
                        value.printStackTrace();
                        System.exit(-2);
                    }
                });
            } else {
                if (count == 0) {
                    start = System.currentTimeMillis();
                }
                if (count % 1000 == 0) {
                    System.out.println(String.format("Received %d messages.", count));
                }
                count++;
            }
            ack.run();
        }
    });
    connection.connect(new Callback<Void>() {
        @Override
        public void onSuccess(Void value) {
            Topic[] topics = { new Topic(destination, QoS.AT_LEAST_ONCE) };
            connection.subscribe(topics, new Callback<byte[]>() {
                public void onSuccess(byte[] qoses) {
                }

                public void onFailure(Throwable value) {
                    value.printStackTrace();
                    System.exit(-2);
                }
            });
        }

        @Override
        public void onFailure(Throwable value) {
            value.printStackTrace();
            System.exit(-2);
        }
    });

    // Wait forever..
    synchronized (Listener.class) {
        while (true)
            Listener.class.wait();
    }
}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from w ww.  j a v a 2s. c o m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}