Tuesday, November 29, 2011

Creating a Thread



Java defines two ways in which this can be accomplished:
  • You can implement the Runnable interface.
  • You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Threads in Java


Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.
I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.


The Arrays Class



The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
SNMethods with Description
1public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
3public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
4public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)

Java String valueOf example.


  1. /*
  2. Java String valueOf example.
  3. This Java String valueOf example describes how various java primitives and Object
  4. are converted to Java String object using String valueOf method.
  5. */
  6.  
  7. public class JavaStringValueOfExample{
  8.  
  9. public static void main(String args[]){
  10.  
  11. /*
  12.   Java String class defines following methods to convert various Java primitives to
  13.   Java String object.
  14.   1) static String valueOf(int i)
  15.   Converts argument int to String and returns new String object representing
  16.   argument int.
  17.   2) static String valueOf(float f)
  18.   Converts argument float to String and returns new String object representing
  19.   argument float.
  20.   3) static String valueOf(long l)
  21.   Converts argument long to String and returns new String object representing
  22.   argument long.
  23.   4) static String valueOf(double i)
  24.   Converts argument double to String and returns new String object representing
  25.   argument double.
  26.   5) static String valueOf(char c)
  27.   Converts argument char to String and returns new String object representing
  28.   argument char.
  29.   6) static String valueOf(boolean b)
  30.   Converts argument boolean to String and returns new String object representing
  31.   argument boolean.
  32.   7) static String valueOf(Object o)
  33.   Converts argument Object to String and returns new String object representing
  34.   argument Object.
  35.   */
  36.  
  37. int i=10;
  38. float f = 10.0f;
  39. long l = 10;
  40. double d=10.0d;
  41. char c='a';
  42. boolean b = true;
  43. Object o = new String("Hello World");
  44.  
  45. /* convert int to String */
  46. System.out.println( String.valueOf(i) );
  47. /* convert float to String */
  48. System.out.println( String.valueOf(f) );
  49. /* convert long to String */
  50. System.out.println( String.valueOf(l) );
  51. /* convert double to String */
  52. System.out.println( String.valueOf(d) );
  53. /* convert char to String */
  54. System.out.println( String.valueOf(c) );
  55. /* convert boolean to String */
  56. System.out.println( String.valueOf(b) );
  57. /* convert Object to String */
  58. System.out.println( String.valueOf(o) );
  59.  
  60. }
  61.  
  62. }
  63.  
  64. /*
  65. OUTPUT of the above given Java String valueOf Example would be :
  66. 10
  67. 10.0
  68. 10
  69. 10.0
  70. a
  71. true
  72. true
  73. Hello World
  74. */

Java String split example.


  1. /*
  2. Java String split example.
  3. This Java String split example describes how Java String is split into multiple
  4. Java String objects.
  5. */
  6.  
  7. public class JavaStringSplitExample{
  8.  
  9. public static void main(String args[]){
  10. /*
  11.   Java String class defines following methods to split Java String object.
  12.   String[] split( String regularExpression )
  13.   Splits the string according to given regular expression.
  14.   String[] split( String reularExpression, int limit )
  15.   Splits the string according to given regular expression. The number of resultant
  16.   substrings by splitting the string is controlled by limit argument.
  17.   */
  18.  
  19. /* String to split. */
  20. String str = "one-two-three";
  21. String[] temp;
  22.  
  23. /* delimiter */
  24. String delimiter = "-";
  25. /* given string will be split by the argument delimiter provided. */
  26. temp = str.split(delimiter);
  27. /* print substrings */
  28. for(int i =0; i < temp.length ; i++)
  29. System.out.println(temp[i]);
  30.  
  31. /*
  32.   IMPORTANT : Some special characters need to be escaped while providing them as
  33.   delimiters like "." and "|".
  34.   */
  35.  
  36. System.out.println("");
  37. str = "one.two.three";
  38. delimiter = "\\.";
  39. temp = str.split(delimiter);
  40. for(int i =0; i < temp.length ; i++)
  41. System.out.println(temp[i]);
  42.  
  43. /*
  44.   Using second argument in the String.split() method, we can control the maximum
  45.   number of substrings generated by splitting a string.
  46.   */
  47.  
  48. System.out.println("");
  49. temp = str.split(delimiter,2);
  50. for(int i =0; i < temp.length ; i++)
  51. System.out.println(temp[i]);
  52.  
  53. }
  54.  
  55. }
  56.  
  57. /*
  58. OUTPUT of the above given Java String split Example would be :
  59. one
  60. two
  61. three
  62. one
  63. two
  64. three
  65. one
  66. two.three
  67. */

Java String compare example.


  1. /*
  2. Java String compare example.
  3. This Java String compare example describes how Java String is compared with another
  4. Java String object or Java Object.
  5. */
  6.  
  7. public class JavaStringCompareExample{
  8.  
  9. public static void main(String args[]){
  10.  
  11. /*
  12.   Java String class defines following methods to compare Java String object.
  13.   1) int compareTo( String anotherString )
  14.   compare two string based upon the unicode value of each character in the String.
  15.   Returns negative int if first string is less than another
  16.   Returns positive int if first string is grater than another
  17.   Returns 0 if both strings are same.
  18.   2) int compareTo( Object obj )
  19.   Behaves exactly like compareTo ( String anotherString) if the argument object
  20.   is of type String, otherwise throws ClassCastException.
  21.   3) int compareToIgnoreCase( String anotherString )
  22.   Compares two strings ignoring the character case of the given String.
  23.   */
  24.  
  25. String str = "Hello World";
  26. String anotherString = "hello world";
  27. Object objStr = str;
  28.  
  29. /* compare two strings, case sensitive */
  30. System.out.println( str.compareTo(anotherString) );
  31. /* compare two strings, ignores character case */
  32. System.out.println( str.compareToIgnoreCase(anotherString) );
  33. /* compare string with object */
  34. System.out.println( str.compareTo(objStr) );
  35.  
  36. }
  37.  
  38. }
  39.  
  40. /*
  41. OUTPUT of the above given Java String compare Example would be :
  42. -32
  43. 0
  44. 0
  45. */

How to find the most appropriate Keywords?

  🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...