Monday, January 12, 2015

[Java] 3 Examples to use Runnable

Method 1:


import java.io.IOException;

class Cal implements Runnable {
    private char id ;
    private int number;
   
    Cal(char id, int number){
        this.id=id;
        this.number = number;
    }
   
    public void run() {
        long sum=0;
        for (int i=1;i<number;i++) {
            sum = sum + i;
        }
        System.out.println("The value of " + id + " is " + sum);
    }//EOF run()
}//EOF cal()
   

public class JavaApplication2  {
    public static void main(String[] args) throws IOException {
        Thread calx = new Thread(new Cal('x',100000));
        Thread caly = new Thread(new Cal('y',10));

        calx.start();
        caly.start();
    }
}
 Result of method 1:

 Method 2
import java.io.IOException;

class Cal implements Runnable {
    private char id ;
    private int number;
   
    Cal(char id, int number){
        this.id=id;
        this.number = number;
    }
   
    public void start(){
        Thread threadx = new Thread(this);
        threadx.start();
    }

   
    public void run() {
        long sum=0;
        for (int i=1;i<number;i++) {
            sum = sum + i;
        }
        System.out.println("The value of " + id + " is " + sum);
    }//EOF run()
}//EOF cal()
   

public class JavaApplication2  {
    public static void main(String[] args) throws IOException {
        Cal calx = new Cal('a',100000);
        Cal caly = new Cal('b',10);

        calx.start();
        caly.start();
    }
}
 Result of method 2:

Method 3
import java.io.IOException;

class Cal implements Runnable {
    private char id ;
    private int number;
   
    Cal(char id, int number){
        this.id=id;
        this.number = number;
        new Thread(this).start();
    }
   
    public void run() {
        long sum=0;
        for (int i=1;i<number;i++) {
            sum = sum + i;
        }
        System.out.println("The value of " + id + " is " + sum);
    }//EOF run()
}//EOF cal()
   

public class JavaApplication2  {
    public static void main(String[] args) throws IOException {
        new Cal('a',100000);
        new Cal('b',10);

    }
}
 Result of method 3:

No comments :

Post a Comment