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 runTaskLater(Runnable runnable) {
    Task task = new Task() {
        @Override// w w w.  jav  a 2s  . co  m
        protected Object call() throws Exception {
            runnable.run();
            return null;
        }
    };

    new Thread(task).start();

}

From source file:Main.java

public static Thread runAsThread(Runnable runnable, boolean daemon) {
    Thread thread = new Thread(runnable);
    thread.setDaemon(daemon);/*from w w  w  .  j a  v a  2s  .  co m*/
    thread.start();
    return thread;
}

From source file:Main.java

public static void sendWoLMagicPacket(final String broadcastIp, final String macAddress) {
    new Thread(new Runnable() {
        @Override//ww w.  j  a va 2s  .  co m
        public void run() {
            try {
                byte[] macBytes = getMacBytes(macAddress);
                byte[] bytes = new byte[6 + 16 * macBytes.length];
                for (int i = 0; i < 6; i++) {
                    bytes[i] = (byte) 0xff;
                }
                for (int i = 6; i < bytes.length; i += macBytes.length) {
                    System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
                }

                InetAddress address = InetAddress.getByName(broadcastIp);
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 9);
                DatagramSocket socket = new DatagramSocket();
                socket.send(packet);
                socket.close();

                packet = new DatagramPacket(bytes, bytes.length, address, 7);
                socket = new DatagramSocket();
                socket.send(packet);
                socket.close();

                Log.e("WAKE_UP", "Wake-on-LAN packet sent.");
                final String output = getStringFromBytes(bytes);
                Log.i("WAKE_UP", output);
            } catch (Exception e) {
                Log.e("WAKE_UP", "Failed to send Wake-on-LAN packet: " + e);

            }
        }
    }).start();
}

From source file:Main.java

public static void clearAppCache(final Context context, final Handler handler) {
    new Thread(new Runnable() {

        @Override/*from w w w  .j  a  v  a 2  s .  c o m*/
        public void run() {
            File cacheDir = new File(context.getCacheDir().getPath(), DEFAULT_CACHE_DIR);
            clearCacheFolder(cacheDir, System.currentTimeMillis());
            handler.sendEmptyMessage(1);
        }
    }).start();

}

From source file:Main.java

public static void showViewWithAnim(final View view, @AnimRes final int anim, final int delay) {
    new Thread(new Runnable() {
        @Override//  w ww .j  av  a2 s.  c om
        public void run() {
            sleep(delay);

            ((Activity) view.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    view.setVisibility(View.VISIBLE);
                    view.startAnimation(AnimationUtils.loadAnimation(view.getContext(), anim));

                }
            });
        }
    }).start();
}

From source file:Main.java

public static void getNewsJSON(final String url, final Handler handler) {

    new Thread(new Runnable() {
        @Override//from w ww .  j  a  v  a 2  s.c  o m
        public void run() {
            HttpURLConnection conn;
            InputStream is;
            try {
                conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("GET");
                is = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = "";
                StringBuffer result = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                Message msg = new Message();
                msg.obj = result.toString();
                handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:Main.java

public static void downloadResource(final String fileUrl) {
    new Thread(new Runnable() {

        @Override//w  w w  . ja v  a  2 s  . co  m
        public void run() {
            inStream = null;
            isOver = false;
            try {
                URL url = new URL(fileUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                inStream = conn.getInputStream();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            isOver = true;
        }
    }).start();
}

From source file:Main.java

/**
 * Causes <tt>runnable.run()</tt> to be run in the swing thread after a given delay
 * @param runnable the task to run in the swing thread
 * @param delayMillis the delay in milliseconds
 *///  w w w . j  a  va  2s  .co  m
public static void doDelayedInSwing(final Runnable runnable, final long delayMillis) {
    new Thread(() -> {
        try {
            Thread.sleep(delayMillis);
            SwingUtilities.invokeLater(runnable);
        } catch (InterruptedException e) {
            // ignore
        }
    }).start();
}

From source file:Main.java

public static Thread getBackgroundThread(Runnable runnable) {
    Thread thread = new Thread(runnable);
    thread.setDaemon(true); // will not block JVM shutdown
    return thread;
}

From source file:com.kactech.otj.examples.Faucet.java

public static void main(String[] args) throws Exception {
    String channel = "#opentransactions"
    //"#kactech_test"
    ////from   www  .j a v  a  2 s  .  c  om
    ;
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println("Command-line parsing error: " + e.getMessage());
        help();
        System.exit(-1);
    }
    if (cmd.hasOption('h')) {
        help();
        System.exit(0);
    }
    if (cmd.hasOption('c'))
        channel = cmd.getOptionValue('c');
    Utils.init();
    client = new EClient(new File("faucet_client"), ExamplesUtils.findServer("OT 8coin")
    //ExamplesUtils.findServer("van")
    );
    client.setAssetType(ExamplesUtils.findAsset("silver").assetID);

    client.init();
    PircBotX bot = new PircBotX();

    bot.setName("OTjFaucet");
    bot.setLogin("fast");
    bot.setVerbose(true);
    bot.setAutoNickChange(true);
    bot.setCapEnabled(true);

    final IrcListener listener = new IrcListener(bot, client);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            if (client == null)
                return;
            client.saveState();
            try {
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                client = null;
            }
            try {
                listener.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));
    bot.getListenerManager().addListener(listener);
    try {
        bot.connect("irc.freenode.net");
        bot.joinChannel(channel);
        if (false)
            while (true) {
                Thread.sleep(1000);
            }
        //bot.quitServer("end of test");

        while (bot.isConnected())
            Thread.sleep(100);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        System.out.println("finally");
        bot.disconnect();
        client.saveState();
        client.close();
        client = null;
    }
}