Wednesday, 21 October 2015

Thread implementation Runnable in java example

import java.io.IOException;


public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Second obj = new Second();
Thread t = new Thread(obj);
t.start();
System.in.read();
obj.i = true;
}

}



public class Second implements Runnable{
public boolean i = false;

@Override
public void run() {
// TODO Auto-generated method stub
for(int j=0;j<2000000;j++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I am J " +j);
if(this.i)return;
}
}
}

output:-
I am J 0
I am J 1
I am J 2

I am J 3

No comments:

Post a Comment