Showing posts with label Java Threads. Show all posts
Showing posts with label Java Threads. Show all posts

May 31, 2011

Java threads yield() method

The yield() method is a static method on the Thread class that causes the currently executing thread to go to the runnable state, yielding to a higher priority thread to become the current executing thread. Whether execution of the yield() method will produce the desired result is the prerogative of the Thread Scheduler.


package info.icontraining.threads;

public class MyRunnable implements Runnable {
 
   public static void main(String[] args) {
      Thread t = new Thread(new MyRunnable());
      t.start();
  
      for(int i=0; i<50; i++) {
         System.out.println("Inside main");
      }
   }
 
   public void run() {
      for(int i=0; i<50; i++) {
         System.out.println("Inside run");
         Thread.yield();
      }
   }
}

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();
   }
}