These are very common questions that a beginner Java developer may ask while learning Multi-threading in Java programming.
What are the ways in which one can create a Java Thread ?Answer : There are two ways. 1 : Using Thread class, 2 : Using Runnable Interface.
What is the difference between Thread and Runnable ?Answer : Thread is a class from java.lang.Thread package , where as Runnable is an interface from java.lang.Runtime package.
Should use Thread Class or Runnable interface and Why?Answer : It depends, but as much as possible we must make use of Runnable interface, We must try to extend a class only when we want to override some behavior. When we extend a class, the two classes are very tightly coupled to each other.
Example: Thread Class: hreadClassExample.javapackage com.code2care.examples;
public class ThreadClassExample extends Thread {
Thread thread;
ThreadClassExample() {
thread = new Thread(this);
System.out.println(thread + " : Started!");
thread.start();
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread : " + thread.getName() + " " + i);
}
}
}
File: ThreadClient.java
package com.code2care.examples;
public class ThreadClient {
public static void main(String[] args) {
new ThreadClassExample();
}
}
Example: Runnable Interface: RunnableExample.java
package com.code2care.examples;
public class RunnableExample implements Runnable {
Thread thread;
RunnableExample() {
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread : " + thread.getName() + " " + i);
}
}
}
ThreadClient.java
package com.code2care.examples;
public class ThreadClient {
public static void main(String[] args) {
new ThreadClassExample();
}
}
More Posts related to Java,
- Java XML-RPC 3.1.x based web service example
- List of jars required for Struts2 project
- list of jars required for hibernate 4.x.x
- How to create StackOverflow error in java
- Tutorial Java SOAP WebServices JAS-WS with Eclipse J2EE IDE and Tomcat Server Part 1
- import servlet API to eclipse project (javax.servlet cannot be resolved error)
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- Convert String to int in Java
- JSP Hello World Program Tutorial with Eclipse and Tomcat Server
- SharePoint Open in the client application document opens in browser
- Java: TimeZone List with GMT/UTC Offset
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Remove Trailing zeros BigDecimal Java
- [Solution] Java Error Code 1603. Java Update did not complete.
- Maven Eclipse (M2e) No archetypes currently available
- error: file not found: HelloWorld.java
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to check if Java main thread is alive
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- Java XML-RPC java.net.BindException: Address already in use
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end users experience
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- List of jar files for Jax-ws (SOAP) based Java Web Services
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- Maven Unsupported major.minor version 51.0
- hibernate.cfg.xml Configuration and Mapping xml Example
- How to verify if java is installed on the computer and get version detail
- Unhandled exception type InterruptedException : Java Threads
- XmlRpcException ConnectException connection refused error
- Error: Unable to access jarfile jarFileName.jar file [Windows]
- BeanDefinitionStoreException IOException parsing XML document from class path resource [spring.xml]
- How to serialize-deserialize an object in java
- List of Java Keywords
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server
- Struts 2 Hello World Example in Eclipse
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- List of Java versions
- Create simple struts2 project using maven commands
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- Error: Can not find the tag library descriptor for
- connection.url property value in hibernate.cfg.xml for mysql
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Setting Java_Home Environment variable on Windows Operating System
More Posts:
- Hide files and folders on Mac OS X - Mac-OS-X
- Android : Execute some code after back button is pressed - Android
- Bootstrap Nav Menu Dropdown on hover - Bootstrap
- Changing Android Intent Tittle using java code - Android
- Share Image and Text on Instagram from Android App using Share Dialog - Android
- Error 404 Tomcat homepage http://localhost:8080/ not displayed - Tomcat
- Hyperlink in html (anchor tag) without a underline - Html
- Change Max and Min Value of Android Seekbar Programmatically - Android
- Channel 50 SMSes received every few minutes Android Phones - Android
- [Solved] SharePoint Search Internal server error exception - SharePoint
- Adding Sub Headings to Bootstrap Header tags - Html
- How to insert image into Google Sheets cell - Google
- [IRCTC] Indian railways official eRail API 1.1 for developers to get train info - HowTos
- Add Text at Start and End of Each Line Notepad++ - NotepadPlusPlus
- Android AlertDialog Programatically Example - Android