February 8, 2011

Java Threads Synchronization

Create a class MyJob that implements the Runnable interface with an instance variable myString of type String - in the run() method of MyJob, add the following code

myString = ""; // this lines goes in the constructor of the MyJob class

for(int i=0; i<10; i++) {
   myString = myString + i;
   System.out.println("myString being formed by thread: " + Thread.currentThread().getName());
}
System.out.println(myString);

In the main() method of another class Test, spawn 2 threads:

MyJob mj = new MyJob();
Thread t1 = new Thread(mj);
Thread t2 = new Thread(mj);
t1.setName("FirstThread");
t2.setName("SecondThread");
t1.start();
t2.start();

What is the output?

What change would you do to make myString assign an ordered String such as 01234567890123456789?

Solution


MyJob.java

public class MyJob implements Runnable {

   private String MyString;
 
   public MyJob() {
      MyString = "";
   }

   public synchronized void run() {

      for(int i=0; i<10; i++) {
         MyString = MyString + i;
         System.out.println("MyString being formed by thread: "
                     + Thread.currentThread().getName());
      }
      System.out.println(MyString);
   }
}

Test.java

public class Test {

   public static void main(String[] args) {

      MyJob mj = new MyJob();

      Thread t1 = new Thread(mj);
      Thread t2 = new Thread(mj);

      t1.setName("FirstThread");
      t2.setName("SecondThread");

      t1.start();
      t2.start();
   }
}

No comments:

Post a Comment