Java – Naming a Thread with Examples ”; Previous Next Name a Thread while Implementing a Runnable Interface If your class is intended to be executed as a thread and is implementing a Runnable interface. You will need to instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Naming a Thread while extending a Thread Class The second way to create a thread is to create a new class that extends Thread class. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. In order to name the thread, we need to call the super class Thread constructor with name. class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); … } … } Example 1 Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. We”re not passing any name to the Thread and it will print the default names assigned to the threads by the system. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); thread1.start(); thread2.start(); } } Output Thread: main, State: New Thread: main, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-0, State: Running Thread: Thread-0, 4 Thread: Thread-0, 3 Thread: Thread-1, State: Running Thread: Thread-0, 2 Thread: Thread-1, 4 Thread: Thread-0, 1 Thread: Thread-1, 3 Thread: Thread-0, State: Dead Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Print Page Previous Next Advertisements ”;
Category: Java
Java – Data Structures
Java – Data Structures ”; Previous Next The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes − Enumeration BitSet Vector Stack Dictionary Hashtable Properties All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter − The Enumeration The Enumeration interface isn”t itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure. For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements. Example Following is an example showing usage of Enumeration for a Vector. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<>(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday To have more detail about this interface, check The Enumeration. The BitSet The BitSet class implements a group of bits or flags that can be set and cleared individually. This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate. Example The following program illustrates several of the methods supported by BitSet data structure − import java.util.BitSet; public class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i = 0; i < 16; i++) { if((i % 2) == 0) bits1.set(i); if((i % 5) != 0) bits2.set(i); } System.out.println(“Initial pattern in bits1: “); System.out.println(bits1); System.out.println(“nInitial pattern in bits2: “); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println(“nbits2 AND bits1: “); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println(“nbits2 OR bits1: “); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println(“nbits2 XOR bits1: “); System.out.println(bits2); } } Output Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {} The Vector The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements. Like an array, elements of a Vector object can be accessed via an index into the vector. The nice thing about using the Vector class is that you don”t have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary. Example The following program illustrates several of the methods supported by Vector collection − import java.util.*; public class VectorDemo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println(“Initial size: ” + v.size()); System.out.println(“Initial capacity: ” + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println(“Capacity after four additions: ” + v.capacity()); v.addElement(new Double(5.45)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println(“First element: ” + (Integer)v.firstElement()); System.out.println(“Last element: ” + (Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println(“Vector contains 3.”); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println(“nElements in vector:”); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + ” “); System.out.println(); } } Output Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity: 5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12 The Stack The Stack class implements a last-in-first-out (LIFO) stack of elements. You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off. Example The following program illustrates several of the methods supported by Stack collection − import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println(“push(” + a + “)”); System.out.println(“stack: ” + st); } static void showpop(Stack st) { System.out.print(“pop -> “); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println(“stack: ” + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println(“stack: ” + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println(“empty stack”); } } } Output stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack The Dictionary The Dictionary class is an abstract class that defines a data structure for mapping keys to values. This is useful in cases where you want to be able to access data via a particular key rather than an integer index. Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation. Example The following example shows the usage of Java Dictionary keys() method. We”re creating a dictionary instance using Hashtable object of Integer, Integer. Then we”ve added few elements to it. An enumeration is retrieved using keys() method and enumeration is then iterated to print the keys of the dictionary. package com.tutorialspoint; import java.util.Enumeration; import java.util.Dictionary; import java.util.Hashtable; public class DictionaryDemo { public static void main(String[] args) { // create a new hashtable Dictionary<Integer, Integer> dictionary = new Hashtable<>();
Java – Generics
Java – Generics ”; Previous Next It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering. Why Generics are used in Java? Generics are used to create such classes, interfaces, and methods with parameters that can operate on different data types along. This feature was introduced in Java 5. Java – Generics Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements. Advantage of Java Generics No scarification of type-safety No requirement of type-casting Compile-time checking Code reusability and improved performance Types of Java Generics Generic Methods You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Rules to Define Generic Methods Following are the rules to define Generic Methods − All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method”s return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. A generic method”s body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). Example of Java Generic Methods Following example illustrates how we can print an array of different type using a single Generic method − public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for(E element : inputArray) { System.out.printf(“%s “, element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { ”H”, ”E”, ”L”, ”L”, ”O” }; System.out.println(“Array integerArray contains:”); printArray(intArray); // pass an Integer array System.out.println(“nArray doubleArray contains:”); printArray(doubleArray); // pass a Double array System.out.println(“nArray characterArray contains:”); printArray(charArray); // pass a Character array } } Output Array integerArray contains: 1 2 3 4 5 Array doubleArray contains: 1.1 2.2 3.3 4.4 Array characterArray contains: H E L L O Bounded Type Parameters There may be times when you”ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter”s name, followed by the extends keyword, followed by its upper bound. Example of Bounded Type Parameters Following example illustrates how extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces). This example is Generic method to return the largest of three Comparable objects − public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf(“Max of %d, %d and %d is %dnn”, 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf(“Max of %.1f,%.1f and %.1f is %.1fnn”, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf(“Max of %s, %s and %s is %sn”,”pear”, “apple”, “orange”, maximum(“pear”, “apple”, “orange”)); } } Output Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear Generic Classes A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters. Example of Generic Classes Following example illustrates how we can define a generic class − public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String(“Hello World”)); System.out.printf(“Integer Value :%dnn”, integerBox.get()); System.out.printf(“String Value :%sn”, stringBox.get()); } } Output Integer Value :10 String Value :Hello World Print Page Previous Next Advertisements ”;
Java – Directories
Java – Directory Operations ”; Previous Next Directory in Java A directory is a File which can contain a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories. Creating Directories There are two useful File utility methods, which can be used to create directories − The mkdir() method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. The mkdirs() method creates both a directory and all the parents of the directory. Example to Create Directory in Java Following example creates “/tmp/user/java/bin” directory − package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String args[]) { String dirname = “/tmp/user/java/bin”; File directory = new File(dirname); // Create directory now. directory.mkdirs(); // create new file object File file = new File(“/tmp/user/java/bin”); System.out.println(file.exists()); } } Output Compile and execute the above code to create “/tmp/user/java/bin” folders. true Note − Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly. Listing (Reading) Directories You can use list() method provided by File object to list down all the files and directories available in a directory as follows − Example to Read (List) a Directory in Java package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File(“/tmp”); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } } catch (Exception e) { // if any error occurs e.printStackTrace(); } } } Output This will produce the following result based on the directories and files available in your /tmp directory − user Deleting Directories You can use delete() method provided by File object to delete a directory as follows − Example to Delete a Directory in Java package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String[] args) { File file = new File(“/tmp/user/java/bin”); if(file.exists()) { boolean success = file.delete(); if (success) { System.out.println(“The directory has been successfully deleted.”); }else { System.out.println(“The directory deletion failed.”); } }else { System.out.println(“The directory is not present.”); } } } Output This will produce the following result based on the directories and files available in your /tmp directory − The directory has been successfully deleted. Print Page Previous Next Advertisements ”;
Java – try-with-resources
Java – Try with Resources ”; Previous Next Try with Resources The Java try-with-resources statement is a try statement that is used for declaring one or more resources such as streams, sockets, databases, connections, etc. These resources must be closed while the program is being finished. The try-with-resources statement closes the resources at the end of the statement. The try-with-resources feature was introduced in Java7. The try-with-resources can also be a replacement for try-catch-finally with resources objects. The try-with-resources statement is also referred as “Automatic Resource Management” and it was introduced in Java7. This statement is a replacement of try-catch-finally-statement if you are working resources objects. Syntax of Try with Resources To use this statement, you simply need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of try-with-resources statement: try(resources declarations) { // use of the resources } catch(Exception e) { // exception handling } For example, opening a file with try-with-resources: try(FileReader fr = new FileReader(“file path”)) { // use the resource } catch () { // body of catch } } Following is the program that reads the data in a file using try-with-resources statement. Example: Try with Resources in Java In this program, we”re creating the FileReader object within try with resources statement. FileReader fr, reference is declared within the try statement and we need not to remember to close it in finally block as it will be closed automatically by JVM so that there is no memory leak or loose connection possibility. import java.io.FileReader; import java.io.IOException; public class Try_withDemo { public static void main(String args[]) { try(FileReader fr = new FileReader(“E://file.txt”)) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); } } } Try with Resources having Multiple Resources You can also declare multiple resource inside a try block. Consider the below-given example, // This example is to use Try with Resources // with multiple Resources import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class Main { public static void main(String[] args) { // try block with multiple resources try ( FileReader fileReader = new FileReader(“file1.txt”); BufferedReader bufferedReader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter(“file2.txt”); PrintWriter printWriter = new PrintWriter(fileWriter) ) { String line; while ((line = bufferedReader.readLine()) != null) { // Read content line by line and write it // to the output (file2.txt) file printWriter.println(line); } System.out.println(“Content copied.”); } catch (IOException e) { e.printStackTrace(); } } } Example: Without Try with Resources In the following program, we are reading data from a file using FileReader and we are closing it using finally block. In this program, we”re creating the FileReader object within try block. FileReader fr, reference is declared outside the try block so that it is accessible outside the try block and we need to remember to close it in finally block or before program exits so that there is no memory leak or loose connection possibility. import java.io.File; import java.io.FileReader; import java.io.IOException; public class ReadData_Demo { public static void main(String args[]) { FileReader fr = null; try { File file = new File(“file.txt”); fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); }finally { try { fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } Try with Resources: Points to Remember Following points are to be kept in mind while working with try-with-resources statement. To use a class with try-with-resources statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime. You can declare more than one class in try-with-resources statement. While you declare multiple classes in the try block of try-with-resources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block. The resource declared in try gets instantiated just before the start of the try-block. The resource declared at the try block is implicitly declared as final. try with resources improvement with Java 9 Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we”ll use BufferedReader as resource to read a string and then BufferedReader is to be closed. Before Java 9 import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData(“test”)); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } } Output Let us compile and run the above program, this will produce the following result − test Here we need to declare a resource br1 within try statment and then use it. In Java9, we don”t need to declare br1 anymore and following program will give the same result. Java 9 onwards import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData(“test”)); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } } Output Let us compile and run the above program, this will produce the following result
Java – Thread Priority
Java – Thread Priority ”; Previous Next Priority of a Thread in Java Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. You can get and set the priority of a Thread. Thread class provides methods and constants for working with the priorities of a Thread. Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. Built-in Property Constants of Thread Class Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). MIN_PRIORITY: Specifies the minimum priority that a thread can have. NORM_PRIORITY: Specifies the default priority that a thread is assigned. MAX_PRIORITY: Specifies the maximum priority that a thread can have. Thread Priority Setter and Getter Methods Thread.getPriority() Method: This method is used to get the priority of a thread. Thread.setPriority() Method: This method is used to set the priority of a thread, it accepts the priority value and updates an existing priority with the given priority. Example of Thread Priority in Java In this example, we”re showing a simple one thread program where we”re not declaring any thread and checking the thread name and priority in the program execution. package com.tutorialspoint; public class TestThread { public void printName() { System.out.println(“Thread Name: ” + Thread.currentThread().getName()); System.out.println(“Thread Priority: ” +Thread.currentThread().getPriority()); } public static void main(String args[]) { TestThread thread = new TestThread(); thread.printName(); } } Output Thread Name: main Thread Priority: 5 More Examples of Thread Priority Example 1 In this example, we”ve created a ThreadDemo class which extends Thread class. We”ve created three threads. Each thread is assigned a priority. In run() method, we”re printing the priorities and in output, it is reflecting in threads execution. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread Name: ” + Thread.currentThread().getName() + “, Thread Priority: ” +Thread.currentThread().getPriority()); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.setPriority(Thread.MAX_PRIORITY); thread2.setPriority(Thread.MIN_PRIORITY); thread3.setPriority(Thread.NORM_PRIORITY); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Name: Thread-2, Thread Priority: 5 Thread Name: Thread-1, Thread Priority: 1 Thread Name: Thread-0, Thread Priority: 10 Thread: Thread-1, 4 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-0, 4 Thread: Thread-1, 2 Thread: Thread-2, 3 Thread: Thread-0, 3 Thread: Thread-0, 2 Thread: Thread-0, 1 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. We”ve created three threads. As we”re not setting any priority, each thread has a normal priority. In run() method, we”re printing the priorities and in output, threads are executing in any order. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread Name: ” + Thread.currentThread().getName() + “, Thread Priority: ” +Thread.currentThread().getPriority()); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Name: Thread-1, Thread Priority: 5 Thread Name: Thread-2, Thread Priority: 5 Thread Name: Thread-0, Thread Priority: 5 Thread: Thread-2, 4 Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-0, 4 Thread: Thread-2, 2 Thread: Thread-1, 2 Thread: Thread-2, 1 Thread: Thread-0, 3 Thread: Thread-1, 1 Thread: Thread-0, 2 Thread: Thread-0, 1 Print Page Previous Next Advertisements ”;
Java – Thread Pools
Java – Thread Pools ”; Previous Next Thread Pools A thread pool is a collection of pre-initialized threads. The general plan behind a thread pool is to form variety of threads at method startup and place them into a pool, wherever they sit and expect work. once a server receives a call for participation, it awakens a thread from this pool−if one is available−and passes it the request for service. Once the thread completes its service, it returns to the pool and awaits a lot of work. If the pool contains no accessible thread, the server waits till one becomes free. Why Use Thread Pools in Java? It saves time as a result of there”s no need to produce new thread. It is utilized in Servlet and JSP wherever instrumentality creates a thread pool to method the request. Creating Thread Pools in Java Java provides a java.util.concurrent.Executors class provides couple of methods to create a thread pools. Executors Class Methods Following are few important and useful methods this class to create Thread Pools – Sr.No. Method & Description 1 public static ExecutorService newCachedThreadPool() Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. 2 public static ExecutorService newFixedThreadPool(int nThreads) Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. 3 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically. 4 public static ExecutorService newWorkStealingPool() Creates a work-stealing thread pool using all available processors as its target parallelism level. Creating a Thread Pool Using newFixedThreadPool() Method A fixed thread pool obtainted by calling the static newFixedThreadPool() method of Executors class. Syntax ExecutorService fixedPool = Executors.newFixedThreadPool(2); Where, Maximum 2 threads will be active to process tasks. If more than 2 threads are submitted then they are held in a queue until threads become available. A new thread is created to take its place if a thread terminates due to failure during execution shutdown on executor is not yet called. Any thread exists till the pool is shutdown. Example: Creating a Thread Pool Using newFixedThreadPool() Method The following TestThread program shows usage of Executors newFixedThreadPool() method to create a thread pool of two threads. We”re using a ThreadPoolExecutor object and initialized with newFixedThreadPool(2), a fix thread pool of size 2. Then we”re printing various attributes of the threadpool. Then we”re adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes. package com.tutorialspoint; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution System.out.println(“Core threads: ” + pool.getCorePoolSize()); System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println(“Running Task! Thread Name: ” + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println(“Task Completed! Thread Name: ” + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } } Output Largest executions: 0 Maximum allowed threads: 2 Current threads in pool: 0 Currently executing threads: 0 Total number of threads(ever scheduled): 0 Core threads: 2 Largest executions: 2 Maximum allowed threads: 2 Current threads in pool: 2 Currently executing threads: 2 Total number of threads(ever scheduled): 4 Running Task! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1 Here although, we”ve submitted four threads but only two threads are executed as ThreadPool is fixed to accept only two threads. Creating a Thread Pool Using newCachedThreadPool() Method A cached thread pool obtainted by calling the static newCachedThreadPool() method of Executors class. Syntax ExecutorService executor = Executors.newCachedThreadPool(); Where, newCachedThreadPool method creates an executor having an expandable thread pool. Such an executor is suitable for applications that launch many short-lived tasks. Example: Creating a Thread Pool Using newCachedThreadPool() Method The following TestThread program shows usage of Executors newCachedThreadPool() method to create a expandable thread pool of threads. We”re using a ThreadPoolExecutor object and initialized with newCachedThreadPool(). Then we”re printing various attributes of the threadpool. Then we”re adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes. package com.tutorialspoint; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution System.out.println(“Core threads: ” + pool.getCorePoolSize()); System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println(“Running Task! Thread Name: ” + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println(“Task Completed! Thread Name: ” + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } } Output Largest executions: 0 Maximum allowed threads:
Java – Thread Control
Java – Thread Control ”; Previous Next Java Thread Control Core Java provides complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed, or stopped completely based on your requirements. There are various static methods which you can use on thread objects to control their behavior. Methods for Controlling Java Thread Following table lists down the methods for controlling a thread in Java: − Sr.No. Method & Description 1 public void suspend() This method puts a thread in the suspended state and can be resumed using resume() method. 2 public void stop() This method stops a thread completely. 3 public void resume() This method resumes a thread, which was suspended using suspend() method. 4 public void wait() Causes the current thread to wait until another thread invokes the notify(). 5 public void notify() Wakes up a single thread that is waiting on this object”s monitor. Be aware that the latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives. Example of Thread Control in Java class RunnableDemo implements Runnable { public Thread t; private String threadName; boolean suspended = false; RunnableDemo( String name) { threadName = name; System.out.println(“Creating ” + threadName ); } public void run() { System.out.println(“Running ” + threadName ); try { for(int i = 10; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); // Let the thread sleep for a while. Thread.sleep(300); synchronized(this) { while(suspended) { wait(); } } } } catch (InterruptedException e) { System.out.println(“Thread ” + threadName + ” interrupted.”); } System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } void suspend() { suspended = true; } synchronized void resume() { suspended = false; notify(); } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( “Thread-1”); R1.start(); RunnableDemo R2 = new RunnableDemo( “Thread-2”); R2.start(); try { Thread.sleep(1000); R1.suspend(); System.out.println(“Suspending First Thread”); Thread.sleep(1000); R1.resume(); System.out.println(“Resuming First Thread”); R2.suspend(); System.out.println(“Suspending thread Two”); Thread.sleep(1000); R2.resume(); System.out.println(“Resuming thread Two”); } catch (InterruptedException e) { System.out.println(“Main thread Interrupted”); }try { System.out.println(“Waiting for threads to finish.”); R1.t.join(); R2.t.join(); } catch (InterruptedException e) { System.out.println(“Main thread Interrupted”); } System.out.println(“Main thread exiting.”); } } The above program produces the following output − Output Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 10 Running Thread-2 Thread: Thread-2, 10 Thread: Thread-1, 9 Thread: Thread-2, 9 Thread: Thread-1, 8 Thread: Thread-2, 8 Thread: Thread-1, 7 Thread: Thread-2, 7 Suspending First Thread Thread: Thread-2, 6 Thread: Thread-2, 5 Thread: Thread-2, 4 Resuming First Thread Suspending thread Two Thread: Thread-1, 6 Thread: Thread-1, 5 Thread: Thread-1, 4 Thread: Thread-1, 3 Resuming thread Two Thread: Thread-2, 3 Waiting for threads to finish. Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Main thread exiting. java_multithreading.htm Print Page Previous Next Advertisements ”;
Java – Arrays
Java – Arrays ”; Previous Next What are Arrays in Java? Java provides a data structure called the array, which stores a fixed-size sequential collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. Declaring Array Variables To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable − Syntax dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way. Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example The following code snippets are examples of this syntax − double[] myList; // preferred way. or double myList[]; // works but not preferred way. Creating Arrays You can create an array by using the new operator with the following syntax − Syntax arrayRefVar = new dataType[arraySize]; The above statement does two things − It creates an array using new dataType[arraySize]. It assigns the reference of the newly created array to the variable arrayRefVar. Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − dataType[] arrayRefVar = new dataType[arraySize]; Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, …, valuek}; The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1. Example Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − double[] myList = new double[10]; Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9. Processing Arrays When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. Example: Creating, Iterating and Performing Other Operations on Arrays public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + ” “); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println(“Total is ” + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println(“Max is ” + max); } } This will produce the following result − Output 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5 The foreach Loops with Arrays JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. The following code displays all the elements in the array myList − Example: Displaying All Elements of an Arrays public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } } This will produce the following result − Output 1.9 2.9 3.4 3.5 Passing Arrays to Methods Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array − Example public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ” “); } } You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 − Example printArray(new int[]{3, 1, 2, 6, 4, 2}); Returning an Array from a Method A method may also return an array. For example, the following method returns an array that is the reversal of another array − Example public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length – 1; i < list.length; i++, j–) { result[j] = list[i]; } return result; } 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. Sr.No. Method & Description 1 public 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, it returns ( – (insertion point + 1)). 2 public 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 primitive data types (Byte, short, Int, etc.) 3 public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types
Java – Shutdown Hook
Java – JVM Shutdown Hook ”; Previous Next JVM Shutdown The following are the two different ways for JVM shutdown – A controlled process: JVM starts to shut down its process if the System.exit() method is called, CTRL+C is pressed, or if the last non-daemon thread terminates. An abrupt manner: JVM starts to shut down its process if it receives a kill signal, the Runtime.getRuntime().halt() method is called, or any kind of OS panic. JVM Shutdown Hook A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. JVM Shutdown Hook: The addShutdownHook(Thread hook) Method The Runtime addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook. Declaration Following is the declaration for java.lang.Runtime.addShutdownHook() method public void addShutdownHook(Thread hook) Parameters hook − An initialized but unstarted Thread object. Return Value This method does not return a value. Exception IllegalArgumentException − If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run. IllegalStateException − If the virtual machine is already in the process of shutting down. SecurityException − If a security manager is present and it denies RuntimePermission(“shutdownHooks”). Example of JVM Shutdown Hook In this example, we”re creating a class CustomThread by extending Thread class. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit. package com.tutorialspoint; class CustomThread extends Thread { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { // register CustomThread as shutdown hook Runtime.getRuntime().addShutdownHook(new CustomThread()); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… JVM is shutting down. More Example of JVM Shutdown Hook Example 1 In this example, we”re creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit. package com.tutorialspoint; class CustomThread implements Runnable { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { // register CustomThread as shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(new CustomThread())); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… JVM is shutting down. Example 2 We can remove the shutdown hook as well using removeShutdownHook(). In this example, we”re creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. As last statement, we”re removing the hook using Runtime.getRuntime().removeShutdownHook() method package com.tutorialspoint; class CustomThread implements Runnable { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { Thread hook = new Thread(new CustomThread()); // register Message as shutdown hook Runtime.getRuntime().addShutdownHook(hook); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); Runtime.getRuntime().removeShutdownHook(hook); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… Print Page Previous Next Advertisements ”;