Janki
Threrad
1 Answer(s)      4 years and 6 months ago
Posted in : Java Beginners

Write a Java program to create two theads. First thread should print the string at the interval of 300 ms. Second thread should print the string at the interval of 700 ms. String to be printed should be passed as constructor argument. Thread should be created using Runnable interface.

Advertisement
View Answers

February 26, 2011 at 3:47 PM


Java Thread Example:

class ThreadExample{
    String st1="";
    String st2="";
    ThreadExample(String st1,String st2){
        this.st1=st1;
        this.st2=st2;
    }
    public void display() {

    Runnable readRun1 = new Runnable() {
      public void run() {
           try{
          Thread.sleep(300);
          System.out.println(st1);
       } catch(Exception ex) {
       }  
      }
    };
    Thread thread1 = new Thread(readRun1);
    thread1.start();

Runnable readRun2 = new Runnable() {
      public void run() {
          try{
          Thread.sleep(700);
         System.out.println(st2);
       } catch(Exception ex) {
       }  
      }
    };
    Thread thread2 = new Thread(readRun2);
    thread2.start();
     }
    public static void main(String[] args) 
    { 
        ThreadExample thread=new ThreadExample("Hello","World");
        thread.display();
        }
}









Related Tutorials/Questions & Answers: