Powered by Blogger.

Java Code: Threading in Java Programming in The Real World

Java Threads:

Modern computer performs multiple jobs at the same time. Thread is the process of multi-tasking using CPU, which performs computations. A thread or execution context is composed of three main parts:

1. A virtual CPU.
2. The code that the CPU executes.
3. The data on which the code work.

Thread object for each Runnable:

       Thread thr1 = new Thread(r1);
       Thread thr2 = new Thread(r2);
       thr1.start();
       thr2.start();

The class java.lang.Thread enables us to create and control threads. A process is a program in execution. One or more threads a process. A thread is composed of CPU, code, and data. Code can share multiple threads, two threads can share the same code. We can create thread by implementing Runnable interface (Code 5-1) or by extending Thread class (Code 5-2). Thread class implements the Runnable interface itself. The Runnable interface provides the public void run() method. We override the run() method, which contain the code for CPU execution.

A newly created thread does not start running automatically, we must call its start() method.

1 public class ThreadTest implements Runnable{
2   public void run(){
3     int i =1;
4     while(i<=100){
5        System.out.println(”i:”+i);
6        i++;
7     }
8   }
9
10  public static void main(String[]args){
11    ThreadTest t = new ThreadTest();
12    Thread thread1 = new Thread(t);
13    Thread thread2 = new Thread(t);
14    Thread thread3 = new Thread(t);
15    thread1.start();
16    thread2.start();
17    thread3.start();
18  }
19 }


1  public class MyThread extends Thread{
2    public void run(){
3      int i=1;
4      while(i<=100){
5        System.out.println(”i:”+i);
6        i++;
7      }
8   }
9
10  public static void main(String[]args){
11    Thread thread1 = new MyThread();
12    Thread thread2 = new MyThread();
13    Thread thread3 = new MyThread();
14    thread1.start();
15    thread2.start();
16    thread3.start();
17  }
18 }

Getting started: what are threads, and how to use them in Java:

It's easier to illustrate what a thread is by diving straight in and seeing some code. We're going to write a program that "splits itself" into two simultaneous tasks. One task is to print Hello, world! every second. The other task is to print Goodbye, cruel world! every two seconds. OK, it's a silly example.

For them to run simultaneously, each of these two tasks will run in a separate thread. To define a "task", we create an instance of Runnable. Then we will wrap each of these Runnables around a Thread object.
Runnable

A Runnable object defines an actual task that is to be executed. It doesn't define how it is to be executed (serial, two at a time, three at a time etc), but just what. We can define a Runnable as follows:

Runnable r = new Runnable() {
  public void run() {
    ... code to be executed ...
  }
};

Runnable is actually an interface, with the single run() method that we must provide. In our case, we want the Runnable.run() methods of our two tasks to print a message periodically. So here is what the code could look like:

Runnable r1 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Hello, world!");
        Thread.sleep(1000L);
      }
    } catch (InterruptedException iex) {}
  }
};
Runnable r2 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Goodbye, " +
        "cruel world!");
        Thread.sleep(2000L);
      }
    } catch (InterruptedException iex) {}
  }
};

For now, we'll gloss over a couple of issues, such as how the task ever stops. As you've probably gathered, the Thread.sleep() method essentially "pauses" for the given number of milliseconds, but could get "interrupted", hence the need to catch InterruptedException. We'll come back to this in more detail in the section on Thread interruption and InterruptedException. The most important point for now is that with the Runnable() interface, we're just defining what the two tasks are. We haven't actually set them running yet. And that's where the Thread class comes in.

0 comments:

Post a Comment