Wednesday, March 11, 2015

Java use in thread element program



Suspending a thread

public class SleepingThread extends Thread 
{
   private int countDown = 5;
   private static int threadCount = 0;
   public SleepingThread() 
   {
      super("" + ++threadCount);
      start();
   }
   public String toString() 
    {
       return "#" + getName() + ": " + countDown;
   }
   public void run() 
     {
      while (true) 
        {
         System.out.println(this);
         if (--countDown == 0)
         return;
         try 
         {
            sleep(100);
         }
         catch (InterruptedException e) 
         {
            throw new RuntimeException(e);
         }
      }
   }
   public static void main(String[] args)throws InterruptedException 
   {
      for (int i = 0; i < 5; i++)
      new SleepingThread().join();
      System.out.println("The thread has been suspened.");
   }
}
 
Summation of Numbers
 
import java.io.IOException;
public class AdditionStack 
{
   static int num;
   static int ans;
   static Stack theStack;
   public static void main(String[] args)throws IOException 
    {
      num = 50;
      stackAddition();
      System.out.println("Sum=" + ans);
    }
   public static void stackAddition() 
     {
      theStack = new Stack(10000); 
      ans = 0; 
      while (num > 0) 
     {
         theStack.push(num); 
         --num; 
      }
      while (!theStack.isEmpty()) 
       {
         int newN = theStack.pop(); 
         ans += newN; 
      }
   }
}
class Stack 
{
   private int maxSize; 
   private int[] data;
   private int top; 
   public Stack(int s) 
   {
      maxSize = s;
      data = new int[maxSize];
      top = -1;
   }
   public void push(int p) 
   {
      data[++top] = p;
   }
   public int pop() 
   {
      return data[top--];
   }
   public int peek() 
   {
      return data[top];
   }
   public boolean isEmpty() 
   {
      return (top == -1);
    }
            }
 
First and last element
 
import java.util.LinkedList;
public class Main 
{
 public static void main(String[] args) 
   {
      LinkedList lList = new LinkedList();
      lList.add("100");
      lList.add("200");
      lList.add("300");
      lList.add("400");
      lList.add("500");
      System.out.println("First element of LinkedList is :
      " + lList.getFirst());
      System.out.println("Last element of LinkedList is : 
      " + lList.getLast());
   }
}

No comments:

Post a Comment