GWT Highcharts – Configuration Syntax ”; Previous Next In this chapter, we will showcase the configuration required to draw a chart using the Highcharts API in GWT. Step 1: Create GWT Application Follow the following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the application to verify the result of the implemented logic. Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = “1.0” encoding = “UTF-8″?> <module rename-to = ”helloworld”> <inherits name = ”com.google.gwt.user.User”/> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <inherits name=”org.moxieapps.gwt.highcharts.Highcharts”/> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>GWT Highcharts Showcase</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> <script src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js” /> <script src = “https://code.highcharts.com/highcharts.js” /> </script> </head> <body> </body> </html> We”ll see the updated HelloWorld.java in the end after understanding configurations. Step 2: Create Configurations Create Chart Configure the type, title and sub-title of the chart. Chart chart = new Chart() .setType(Type.SPLINE) .setChartTitleText(“Monthly Average Temperature”) .setChartSubtitleText(“Source: WorldClimate.com”); xAxis Configure the ticker to be displayed on the X-Axis. XAxis xAxis = chart.getXAxis(); xAxis.setCategories(“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”); yAxis Configure the title, plot lines to be displayed on the Y-Axis. YAxis yAxis = chart.getYAxis(); yAxis.setAxisTitleText(“Temperature °C”); yAxis.createPlotLine() .setValue(0) .setWidth(1) .setColor(“#808080”); tooltip Configure the tooltip. Put suffix to be added after value (y-axis). ToolTip toolTip = new ToolTip(); toolTip.setValueSuffix(“°C”); chart.setToolTip(toolTip); legend Configure the legend to be displayed on the right side of the chart along with other properties. legend.setLayout(Legend.Layout.VERTICAL) .setAlign(Legend.Align.RIGHT) .setVerticalAlign(Legend.VerticalAlign.TOP) .setX(-10) .setY(100) .setBorderWidth(0); chart.setLegend(legend); series Configure the data to be displayed on the chart. Series is an array where each element of this array represents a single line on the chart. chart.addSeries(chart.createSeries() .setName(“Tokyo”) .setPoints(new Number[] { 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 }) ); chart.addSeries(chart.createSeries() .setName(“New York”) .setPoints(new Number[] { -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5 }) ); chart.addSeries(chart.createSeries() .setName(“Berlin”) .setPoints(new Number[] { -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0 }) ); chart.addSeries(chart.createSeries() .setName(“London”) .setPoints(new Number[] { 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8 }) ); Step 3: Add the chart to parent panel. We”re adding the chart to root panel. RootPanel.get().add(chart); Example Consider the following example to further understand the Configuration Syntax − HelloWorld.java package com.tutorialspoint.client; import org.moxieapps.gwt.highcharts.client.Chart; import org.moxieapps.gwt.highcharts.client.Legend; import org.moxieapps.gwt.highcharts.client.Series.Type; import org.moxieapps.gwt.highcharts.client.ToolTip; import org.moxieapps.gwt.highcharts.client.XAxis; import org.moxieapps.gwt.highcharts.client.YAxis; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { Chart chart = new Chart() .setType(Type.SPLINE) .setChartTitleText(“Monthly Average Temperature”) .setChartSubtitleText(“Source: WorldClimate.com”); XAxis xAxis = chart.getXAxis(); xAxis.setCategories(“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”); YAxis yAxis = chart.getYAxis(); yAxis.setAxisTitleText(“Temperature °C”); yAxis.createPlotLine() .setValue(0) .setWidth(1) .setColor(“#808080”); ToolTip toolTip = new ToolTip(); toolTip.setValueSuffix(“°C”); chart.setToolTip(toolTip); Legend legend = new Legend(); legend.setLayout(Legend.Layout.VERTICAL) .setAlign(Legend.Align.RIGHT) .setVerticalAlign(Legend.VerticalAlign.TOP) .setX(-10) .setY(100) .setBorderWidth(0); chart.setLegend(legend); chart.addSeries(chart.createSeries() .setName(“Tokyo”) .setPoints(new Number[] { 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 }) ); chart.addSeries(chart.createSeries() .setName(“New York”) .setPoints(new Number[] { -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5 }) ); chart.addSeries(chart.createSeries() .setName(“Berlin”) .setPoints(new Number[] { -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0 }) ); chart.addSeries(chart.createSeries() .setName(“London”) .setPoints(new Number[] { 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8 }) ); RootPanel.get().add(chart); } } Result Verify the result. Print Page Previous Next Advertisements ”;
Category: Java
Environment Setup
GWT Highcharts – Environment Setup ”; Previous Next This tutorial will guide you on how to prepare a development environment to start your work with Highcharts and GWT Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you setup GWT Framework − System Requirement GWT requires JDK 1.6 or higher so the very first requirement is to have JDK installed in your machine. JDK 1.6 or above. Memory no minimum requirement. Disk Space no minimum requirement. Operating System no minimum requirement. Follow the given steps to setup your environment to start with GWT application development. Step 1 – Verify Java Installation on your Machine Now open console and execute the following java command. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems Sr.No. OS & Generated Output 1 Windows java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 2 Linux java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) ava HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 3 Mac java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing) Step 2 – Setup Java Development Kit (JDK) If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle”s Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example Sr.No. OS & Output 1 Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21 2 Linux export JAVA_HOME = /usr/local/java-current 3 Mac export JAVA_HOME = /Library/Java/Home Append Java compiler location to System Path. Sr.No. OS & Output 1 Windows Append the string ;%JAVA_HOME%bin to the end of the system variable, Path. 2 Linux export PATH=$PATH:$JAVA_HOME/bin/ 3 Mac not required Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE. Step 3 – Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine based on your operating system. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display following result − Step 4: Install GWT SDK & Plugin for Eclipse Follow the instructions given at the link Plugin for Eclipse (incl. SDKs) to install GWT SDK & Plugin for Eclipse version installed on your machine. After a successful setup for the GWT plugin, if everything is fine then it should display following screen with Google icon marked with red rectangle as shown below − Step 5: Install Highcharts Download the latest Highcharts jar from its Downloadpage and add it to project”s classpath. Add the following entry in <project-name>.gwt.xml file <inherits name=”org.moxieapps.gwt.highcharts.Highcharts”/> Add the following entry in <project-name>.html file <script src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”/> <script src = “https://code.highcharts.com/highcharts.js”/> <script type=”text/javascript” src=”https://code.highcharts.com/highcharts-3d.js” /> <script type=”text/javascript” src=”https://code.highcharts.com/highcharts-more.js” /> <script src = “https://code.highcharts.com/modules/heatmap.js” /> <script src = “https://code.highcharts.com/modules/treemap.js” /> Print Page Previous Next Advertisements ”;
GWT Highcharts – Pie Charts
GWT Highcharts – Pie Charts ”; Previous Next Pie charts are used to draw pie based charts. In this section, we will discuss the different types of pie based charts. Sr.No. Chart Type & Description 1 Basic Pie Basic pie chart. 2 Pie with Legends Pie chart with Legends. 3 Donut Chart Donut Chart. Print Page Previous Next Advertisements ”;
GWT Highcharts – Scatter Chart ”; Previous Next Following is an example of a basic scatter chart. We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. An example of a basic scatter chart is given below. Configurations Let us now see the additional configurations/steps taken. series Configure the chart type to be scatter based. series.type decides the series type for the chart. Here, the default value is “line”. chart.addSeries(chart.createSeries() .setName(“Observations”) .setType(Type.SCATTER) .setPoints(new Number[] { 1, 1.5, 2.8, 3.5, 3.9, 4.2 }) ); Example HelloWorld.java package com.tutorialspoint.client; import org.moxieapps.gwt.highcharts.client.Chart; import org.moxieapps.gwt.highcharts.client.Series.Type; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { final Chart chart = new Chart() .setChartTitleText(“Scatter plot”); chart.getXAxis() .setMin(-0.5) .setMax(5.5); chart.getYAxis() .setMin(0); chart.addSeries(chart.createSeries() .setName(“Observations”) .setType(Type.SCATTER) .setPoints(new Number[] { 1, 1.5, 2.8, 3.5, 3.9, 4.2 }) ); RootPanel.get().add(chart); } } Result Verify the result. Print Page Previous Next Advertisements ”;
GWT Highcharts – 3D Charts
GWT Highcharts – 3D Charts ”; Previous Next 3D charts are used to draw 3-dimensional charts. In this section, we will discuss the different types of 3D charts. Sr.No. Chart Type & Description 1 3D Column 3D Column Chart. 2 3D Scatter 3D Scatter Chart. 3 3D Pie 3D Pie Chart. Print Page Previous Next Advertisements ”;
GWT Highcharts – Bar Charts
GWT Highcharts – Bar Charts ”; Previous Next Bar charts are used to draw bar based charts. In this section, we will discuss the different types of bar based charts. Sr.No. Chart Type & Description 1 Basic Bar Basic bar chart. 2 Stacked Bar Bar chart having bar stacked over one another. 3 Bar Chart with negative values Bar Chart with negative values. Print Page Previous Next Advertisements ”;
Java – Custom Exception
Java – Custom Exception ”; Previous Next Java Custom Exception The custom exception refers to the creation of your own exception to customize an exception according to the needs. The custom exceptions are derived from the Exception class. Need of Java Custom Exceptions To categorize the exceptions based on the different types of errors in your project. To allow application-level exception handling. Create a Custom Exception in Java To create a custom exception, you need to create a class that must be inherited from the Exception class. Syntax Here is the syntax to create a custom class in Java – class MyException extends Exception { } You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. Rules to Create Custom Exception Keep the following points in mind when writing your own exception classes − All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. Java Custom Exception Example The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods. class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; }else { double needs = amount – balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount. package com.tutorialspoint; public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println(“Depositing $500…”); c.deposit(500.00); try { System.out.println(“nWithdrawing $100…”); c.withdraw(100.00); System.out.println(“nWithdrawing $600…”); c.withdraw(600.00); } catch (InsufficientFundsException e) { System.out.println(“Sorry, but you are short $” + e.getAmount()); e.printStackTrace(); } } } class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; }else { double needs = amount – balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } Output Compile all the above three files and run BankDemo. This will produce the following result − Depositing $500… Withdrawing $100… Withdrawing $600… Sorry, but you are short $200.0 com.tutorialspoint.InsufficientFundsException at com.tutorialspoint.CheckingAccount.withdraw(BankDemo.java:39) at com.tutorialspoint.BankDemo.main(BankDemo.java:14) In next example, we”re declaring our custom exception as RuntimeException to make it as unchecked exception class as below − class MyException extends RuntimeException { } Example to Create Custom Class by Extending Runtime Exception We are extending the predefined RuntimeException class to create your own Exception as an unchecked exception. The following InsufficientFundsException class is a user-defined exception that extends the RuntimeException class, making it a unchecked exception. An RuntimeException class is like any other class, containing useful fields and methods. class InsufficientFundsException extends RuntimeException { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount using unchecked exception. package com.tutorialspoint; public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println(“Depositing $500…”); c.deposit(500.00); System.out.println(“nWithdrawing $100…”); c.withdraw(100.00); System.out.println(“nWithdrawing $600…”); c.withdraw(600.00); } } class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if(amount <= balance) { balance -= amount; }else { double needs = amount – balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } class InsufficientFundsException extends RuntimeException { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } Output Compile and run BankDemo. This will produce the following result − Depositing $500… Withdrawing $100… Withdrawing $600… Exception in thread “main” com.tutorialspoint.InsufficientFundsException at com.tutorialspoint.CheckingAccount.withdraw(BankDemo.java:35) at com.tutorialspoint.BankDemo.main(BankDemo.java:13) Print Page Previous Next Advertisements ”;
Java – Exceptions
Java – Exceptions ”; Previous Next What Is an Exception in Java? An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. Why Exception Occurs? An exception can occur for many different reasons. Following are some scenarios where an exception occurs. A user has entered an invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Java Exception Categories Based on these, we have the following categories of Exceptions. You need to understand them to know how exception handling works in Java. Checked exceptions Unchecked exceptions Errors Java Checked Exceptions A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. Example: Checked Exceptions in Java For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn”t exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]) { File file = new File(“E://file.txt”); FileReader fr = new FileReader(file); } } If you try to compile the above program, you will get the following exceptions. Output C:>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error Note − Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException. Java Unchecked Exceptions An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Example: Unchecked Exceptions in Java For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs. public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num[5]); } } If you compile and execute the above program, you will get the following exception. Output Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8) Java Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Java Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class. Following is a list of most common checked and unchecked Java”s Built-in Exceptions. Java Exception Class Methods Following is the list of important methods available in the Throwable class. Sr.No. Method & Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage(). 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. Catching Exceptions: Exception Handling in Java A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following − Syntax try { // Protected code } catch (ExceptionName e1) { // Catch block } The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example: Demonstrating Exception Handling In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an
Java – Multithreading
Java – Multithreading ”; Previous Next Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Java Multithreading Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. To achieve the multithreading (or, write multithreaded code), you need java.lang.Thread class. Life Cycle of a Thread in Java Multithreading A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. Following are the stages of the life cycle − New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. 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). 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. Create a Thread by Implementing a Runnable Interface If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − Step 1: Implement run() Method As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) Step 2: Instantiate a Thread Object As a second step, you will 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. Step 3: Call Thread using start() Method 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: Create Thread by Implementing Runnable Interface Here is an example that creates a new thread and starts running it − class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Creating ” + threadName ); } public void run() { System.out.println(“Running ” + threadName ); try { for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); // Let the thread sleep for a while. Thread.sleep(50); } } 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 (); } } } 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(); } } Output Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Create a Thread by Extending a Thread Class The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1: Override run() Method You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Step 2: Call Thread using start() Method Once 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: Create Thread by Extending Thread Class Here is the preceding program rewritten to extend the Thread − class ThreadDemo extends Thread { private Thread t; private String threadName;
Java – Interrupting a Thread
Java – Interrupting Thread ”; Previous Next Interrupting a Thread in Java A thread can send an interrupt signal to JVM to interrupt by invoking interrupt on the Thread object for the thread to be interrupted. This means interruption of a thread is caused by any other thread calling the interrupt() method. Methods for Interrupting a Thread The Thread class provides three methods for interrupting a thread – void interrupt() − Interrupts the thread. static boolean interrupted() − Tests whether the current thread has been interrupted. boolean isInterrupted() − Tests whether the thread has been interrupted. Example of Interrupting a Java Thread In this example, we”re creating a Task object which has implemented Runnable interface to act as a thread. Using start() method, we”ve started the thread. As next statement, we”re interrupting the thread using interrupt() method and we”re printing thread properties in run() method. package com.tutorialspoint; public class TestThread { public static void main(String[] args) { System.out.println(“Thread main started”); final Task task = new Task(); final Thread thread = new Thread(task); thread.start(); thread.interrupt(); // calling interrupt() method System.out.println(“Main Thread finished”); } } class Task implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(“[” + Thread.currentThread().getName() + “] Message ” + i); if(Thread.interrupted()) { System.out.println(“This thread was interruped by someone calling this Thread.interrupt()”); System.out.println(“Cancelling task running in thread ” + Thread.currentThread().getName()); System.out.println(“After Thread.interrupted() call, JVM reset the interrupted value to: ” + Thread.interrupted()); break; } } } } Output Thread main started Main Thread finished [Thread-0] Message 0 This thread was interruped by someone calling this Thread.interrupt() Cancelling task running in thread Thread-0 After Thread.interrupted() call, JVM reset the interrupted value to: false Example of Interrupting a Java Thread with InterruptedException Handling In this example, we”re handling the interruption and continuing the thread. We”re creating a Task object which has implemented Runnable interface to act as a thread. Using start() method, we”ve started the thread. As next statement, we”re interrupting the thread using interrupt() method and we”re handling InterruptedException in run() method and printing the details. package com.tutorialspoint; public class TestThread { public static void main(String[] args) { System.out.println(“Thread main started”); final Task task = new Task(); final Thread thread = new Thread(task); thread.start(); thread.interrupt(); // calling interrupt() method System.out.println(“Main Thread finished”); } } class Task implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(“[” + Thread.currentThread().getName() + “] Message ” + i); try { Thread.sleep(50); } catch (InterruptedException e) { System.out.println(“This thread was interruped by someone calling this Thread.interrupt()”); } } } } Output Thread main started Main Thread finished [Thread-0] Message 0 This thread was interruped by someone calling this Thread.interrupt() [Thread-0] Message 1 [Thread-0] Message 2 [Thread-0] Message 3 [Thread-0] Message 4 Example of Checking Whether Thread is Interrupted or Not In this example, we”re showcasing multiple threads and use of interrupted() method to check if a thread is interrupted or not. We”re creating multiple Task objects which has implemented Runnable interface to act as a thread. Using start() method, we”ve starting the threads. Then, we”re interrupting a thread using interrupt() method and using interrupted in run() method, we”re printing the details. package com.tutorialspoint; public class TestThread { public static void main(String[] args) { System.out.println(“Thread main started”); final Task task1 = new Task(); final Thread thread1 = new Thread(task1); final Task task2 = new Task(); final Thread thread2 = new Thread(task2); final Task task3 = new Task(); final Thread thread3 = new Thread(task3); thread1.start(); thread2.start(); thread3.start(); thread1.interrupt(); // calling interrupt() method System.out.println(“Main Thread finished”); } } class Task implements Runnable { @Override public void run() { if(Thread.interrupted()) { System.out.println(“[” + Thread.currentThread().getName() + “] Interrupted “); }else { System.out.println(“[” + Thread.currentThread().getName() + “] Uninterrupted “); } } } Output Thread main started Main Thread finished [Thread-2] Uninterrupted [Thread-0] Interrupted [Thread-1] Uninterrupted Print Page Previous Next Advertisements ”;