Tuesday 23 July 2019

How to kill a thread in JAVA ??

Ans:

'Killing a thread' is not the right phrase to use. Here is one way we can implement graceful exit of the thread:
class TaskThread implements Runnable {

    boolean shouldStop;

    public TaskThread(boolean shouldStop) {
        this.shouldStop = shouldStop;
    }

    @Override
    public void run() {

        System.out.println("Thread has started");

        while (!shouldStop) {
            // do something
        }

        System.out.println("Thread has ended");

    }
public void stop() {
        shouldStop = true;
    }


}
public class ThreadStop
{
public static void main(String[] args)
{
System.out.println("Start");

// Start the thread
TaskThread task = new TaskThread(false);
Thread t = new Thread(task);
t.start();

  // Stop the thread
task.stop();

  System.out.println("End");

}
}

Friday 5 July 2019

JAVA StringBuffer and StringBuilder object conversion to String


We can convert a StringBuffer or StringBuilder object  to String by using toString() method of Object class.
StringConversion.java
class StringConversion
{
          public static void main(String[] args)
          {
                   StringBuffer sb1=new StringBuffer("Silan");
                   StringBuilder sb2=new StringBuilder("Technology");
                   String s1=sb1.toString();
                   String s2=sb2.toString();
                   System.out.println(s1+" "+s2);
          }
}
Output:
Silan Technology


StringConversion1.java
class StringConversion1
{
          public static void main(String[] args)
          {
                   StringBuffer sb1=new StringBuffer("Silan");
                   StringBuffer sb2=new StringBuffer("Silan");
                   String s1=sb1.toString();
                   String s2=sb2.toString();
                   if(s1.equals(s2))
                   {
                             System.out.println("s1 and s2 contents are equal");
                   }
                   else
                   {
                             System.out.println("s1 and s2 contents are not equal");
                   }
          }
}
Output:
s1 and s2 contents are equal