Wednesday, March 12, 2014

Create thread in Java (two ways)

There are two ways you can create new Thread in Java. First one is to implement Runnable. This is more common way of doing this, but if you look at the Thread's code, you will see that Thread only calls run() on Runnable object, so you basically don't need it here. Second way is not to use Runnable, but instead just implement Thread's run() ant that's it!

Using Runnable:
  Thread secondMethod = new Thread(new Runnable() {
      int index = 0;
      @Override
      public void run() {
          try {
              while (index < 100) {
                  int interval = (int) ((Math.random() * 500) + 500);
                  Thread.sleep(interval);
                  System.out.print("*");
                  index++;
              }
          } catch (InterruptedException exc) {
              //Empty
          }
      }
  });
Without Runnable:
Thread firstMethod = new Thread() {
    int index = 0;
    @Override
    public void run() {
        try {
            while (index < 100) {
                int interval = (int) ((Math.random() * 500) + 500);
                sleep(interval);
                System.out.print(".");
                index++;
            }
        } catch (InterruptedException exc) {
            //Empty
        }
    }
};

No comments:

Post a Comment