Skip to main content

Thread in Java and Hooking concept

THREAD:


Thread is the lightweight Process(uses Shared Memory of application).
States:


Mansur, [01.10.18 09:35]
Thread is a lightweight (uses the shared memory of application) process (program in execution in waiting state).
Multiprogramming execution of more than one application (vlc and notepad execute at a time)
Multithreading executes more than one threads in a single application. (in NFS 4 cars are executing at a time)
States of threads:
New state->ready .->running/waiting->dead state
To create thread:
1.Extending Thread Class
it contains start() method.
2.BY implementing Runnable Interface .






Start () method is present in the Thread class. It is used to create Thread. Whenever the Start method of Thread class is called it registers the thread into Thread Scheduler and calls the run method.
Recommendation:
  • we should not override start method in implementing class or extending class otherwise it will become normal method.
  • Start method of thread class calls run method
Run method :
it is available in runnable interface which is overriden by Thread class Run method.Run method is called by start method of Thread Class.


:Recommendation:


we should override the run method in our class to get the desired output of thread.


class Mythread extends Thread
{
public void run ()
{
for(int i=0;i<10 font="" i="">
System.out.println(i+" "+Thread.currentThread().getName());
}
}
class A
{
public static void main(String[] args) {
Mythread t=new Mythread();
t.start();
for(int i=100;i<110 font="" i="">
System.out.println(Thread.currentThread().getName()+i);
}
}




the output of the thread is decided by the thread Scheduler based on the algorithms.
1.Pre-emptive Algorithms.
2.Time-Slicing Algorithms.


On the basis of priority, the order of execution of the thread is decided.


Priority Varies from 1(MIN_PRIORITY) to 10(MAX_PRIORITY).


5 is NORM_PRIORITY. It is default priority of the main thread.
All the thread started by the main thread will also have default priority 5.
Less priority means the execution of that thread will be later.
Whenever we override the start method, the thread will not be created.






Generally, we use Runnable interface to use Threading in Program because the interface has multiple inheritances allowed...if we extends Thread class then we will not be able to extends other class however if we use Interface we can still have other class and interface to extends or implements.




class B
{
public static void main(String[] args) {
new Thread(new Thread(){public void run (){
for(int i=0;i<10 font="" getname="" i="" system.out.println="">
System.out.println("Hello java "+
getName());
}}).start();
new Thread(new Thread(){public void run (){
for(int i=0;i<10 font="" getname="" i="" system.out.println="">
System.out.println("Bye java "+getName());
}}).start();
System.out.println("main "+Thread.currentThread());
}


}




some methods of Thread class:
setName(): to set the name of Thread. Example : t.setName(“Beast Thread”);
getName(): to get the Thread name.Example: t.getnName();
setPriority(int ): to set the priority of the thread.
getPriority() : get the priorirty of the Thread.




Daemon Thread :
  • this process are those process which run in background.
  • daemon thread stops if main thread stops.
The function of Daemon Thread:
setDaemon(boolean): it is used to make the normal thread a Daemon.
Ex: st.etDaemon(true); will make the thread  as a daemon thread.
class demon extends Thread
{
public void run ()
{
for (int i=0;i<20 i="">
System.out.println("user defined Thread with deamon enabled "+i);
try{
Thread.sleep(1);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class B
{
public static void main(String[] args) {
demon t=new demon();
t.setDaemon(true);// now the program terminates of the main thread stops.
//t.setDaemon(false); it will make the thread t to full run.
t.start();
for (int i=0;i<10 i="">
System.out.println("Main thread "+i);
}
}
}
_____________________________some Excpetion related methods_________________________
toString() : when we call toString the exception type and reason also comes.
getmessage():gives the exception only,it prints only the message part of the output printed by the object.
printStackTrace() : gives the whole Stack Trace of Exception.




By default, printStackTrace is called in the case of Exception.






Hook thread will be executed just before the termination of the JVM normally or abnormally.
Hook thread used to have the cleanup code.




Creating Hook thread:
Runtime.getRuntime().addShutdownHook(Thread obj);
Example:


class ShutDownHook
{
  public static void main(String[] args)
  {
  
    Runtime.getRuntime().addShutdownHook(new Thread()
    {
      public void run()
      {
        System.out.println("Shutdown Hook is running !");
      }
    });
    System.out.println("Application Terminating ...");
  }
}


class demon extends Thread
{
public void run ()
{
for (int i=0;i<20 i="">
System.out.println("user defined Thread with deamon enabled "+i);
try{
Thread.sleep(1);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class B
{
public static void main(String[] args) {
demon t=new demon();
t.setDaemon(true);
t.start();
for (int i=0;i<10 i="">
System.out.println("Main thread "+i);
}
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){ System.out.println("shuttind down");
}
});
}
}

Comments

Popular posts from this blog

what is LOREM ipsum and why do designers use it

What is Lorem Ipsum? Lorem Ipsum  is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now...

20 Windows Keyboard Shortcuts You Might Not Know

Global Windows Shortcuts Win+1, 2, 3, 4, etc. will launch each program in your taskbar. It is helpful then to keep your most used programs at the beginning of your task bar so you can open them one right after another. This also works in Windows Vista for the quick launch icons. Win+Alt+1, 2, 3, etc. will open the jump list for each program in the taskbar. You can then use your arrows to select which jump list option you want to open. Win+T will cycle through taskbar programs. This is similar to just hovering over the item with your mouse but you can launch the program with Space or Enter. Win+Home minimizes all programs except current the window. This is similar to the Aero shake and can be disabled with the same registry key. Win+B selects the system tray which isn’t always useful but can come in very handy if your mouse stops working. Win+Up/Down maximizes and restores down the current window so long as that window has the option to be maximized. It is exactly t...

Streamlining Java Web Application Deployment with React WAR Generator

In the ever-evolving world of web development, managing builds and deployments can often be cumbersome and error-prone. Today, we're excited to introduce a tool designed to simplify and streamline this process: the React WAR Generator . What is the React WAR Generator? The React WAR Generator is a Python-based tool that automates the creation of WAR (Web Application Archive) files for Java web applications. It caters specifically to frontend projects built with React or similar frameworks, making it easier to package and deploy your web applications to a Tomcat server. Key Features Profile-Based Builds : With support for multiple profiles ( dev , test , prod , default ), you can build your application according to different environments and configurations. Version File Generation : Optionally generate a version file that integrates versioning information directly into your TypeScript files, ensuring your build versions are always up-to-date. Tomcat Deployment : Simplify your deploy...

Java API call Example using GSON, org.json.json and Jackson [ Simple Get Call] and parsing result as JSON

import com.fasterxml.jackson.databind.JsonNode ; import com.fasterxml.jackson.databind.ObjectMapper ; import com.google.gson.* ; import org.json.JSONArray ; import org.json.JSONObject ; import java.io.* ; import java.net.HttpURLConnection ; import java.net.URL ; public class APICALL { public static void main (String[] args) throws IOException { // String url="https://mocki.io/v1/19a50724-c2e5-46a1-b457-543462cdfde2"; String url= "https://jsonplaceholder.typicode.com/users" ; String line ; StringBuilder resp= new StringBuilder() ; System. out .println(url) ; HttpURLConnection con= (HttpURLConnection) new URL(url).openConnection() ; con.setRequestMethod( "GET" ) ; con.setRequestProperty( "Accept" , "application/json" ) ; System. out .println(con.getResponseMessage()) ; System. out .println(con.getContentType()) ; InputStream inputStream=con.getInput...

keyboard-shortcuts-that-work-in-all-web-browsers

Each major web browser shares a large number of keyboard shortcuts in common. Whether you’re using Mozilla Firefox, Google Chrome, Internet Explorer, Apple Safari, or Opera – these keyboard shortcuts will work in your browser. Each browser also has some of its own, browser-specific shortcuts, but learning the ones they have in common will serve you well as you switch between different browsers and computers. This list includes a few mouse actions, too. Tabs Ctrl+1-8 – Switch to the specified tab, counting from the left. Ctrl+9 – Switch to the last tab. Ctrl+Tab – Switch to the next tab – in other words, the tab on the right. (Ctrl+Page Up also works, but not in Internet Explorer.) Ctrl+Shift+Tab – Switch to the previous tab – in other words, the tab on the left. (Ctrl+Page Down also works, but not in Internet Explorer.) Ctrl+W, Ctrl+F4 – Close the current tab. Ctrl+Shift+T – Reopen the last closed tab. Ctrl+T – Open a new tab. Ctrl+N – Open a new browser window....

How to Put Google Adsense Below Post Title in Blogger?

Adsense is used by majority of expert bloggers for their website monetization because it is a cookie based contextual advertising system that shows targeted ads relevant to the content and reader. As bloggers are paid on per click basis, they try various ad placements on the blog to  increase the revenue  and get maximum clicks on the ad units. Well, on some blogs, you might have seen Adsense ad units placed below the post title. Do you know why? It is because the area just below the post title gets the most exposure and is the best place to put AdSense ad units to increase  Click Through Rate (CTR). Even though ads below post title work like a charm but this doesn’t mean that it will work for you as well. If you want to find out the best AdSense ads placement for your blog, try experimenting by placing ads at various locations such as header, sidebar, footer, etc. You can try other  blog monetization methods  as well to effectively monetize y...

remove virus without antivirus

want  to remove virus without antivirus here it is Start->Run->type cmd in each drive type attrib /s /d it will display the list of all files in that drive along with folders.concntrate on files having SHR attribute.normally virus files have two characteristics 1.SHR attribute 2.Queer name like amvo.exe,r6r.exe,autorun.inf etc. Noteme system files also have this attribute like MSDOS.SYS,IO.SYS etc so before deleting googling about that file will help. to delete these files type c:\>del /f /s /a >> to view the content of files with .inf,.vbs,.c etc i.e files which r not batch files or executables.goto explorer n then goto the required drive or folder n type the filename with extension it wil open up in notepad. >>there is another method also.goto the required location n type attrib -s -h -r filename then use gui to see that hiiden file.if it is not n exe or .bat or then open it with notepad.Here you will get some information like a file na...

Creating an Executable Jar File

Creating a jar File in  Eclipse In  Eclipse  Help contents, expand "Java development user guide" ==> "Tasks" ==> "Creating JAR files."  Follow the instructions for "Creating a new JAR file" or "Creating a new runnable JAR file."The  JAR File  and  Runnable JAR File  commands are for some reason located under the  File menu: click on  Export...  and expand the  Java  node. Creating a jar File in  JCreator You can configure a "tool" that will automate the jar creation process.  You only need to do it once. Click on  Configure/Options . Click on  Tools  in the left column. Click  New , and choose  Create Jar file . Click on the newly created entry  Create Jar File  in the left column under  Tools . Edit the middle line labeled  Arguments:  it should have cvfm $[PrjName].jar manifest.txt *.class Click OK. Now set...

C program to find whether two Strings are cyclic Anagram or not

Example 1.first String: abcd  second string:dabc  output:They are cyclic anagram 2.  first String: abcd  second string:dcab output:They are not  cyclic anagram CODE: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 # include # include int main() { char s[ 100 ], b[ 100 ], temp; int n, len, i; printf( "Enter the String \n " ); scanf( "%s" , s); printf( " \n Entered String=%s" , s); printf( " \n Enter String to be matched->" ); scanf( "%s" , b); printf( " \n Entered String to be matched->%s" , b); len = strlen(s); if (len != strlen(b)) { printf( " \n they are not cyclic anagram \n " ); getchar(); return 0 ; } ...

remove the usb virus instruction

REmOVE VIRUS THAT CAUSES FILES IN REMOVBLE RIVE/PEN DRIVE/MEMORY CARD TO become shortcut. Hello friend You can easily remove VIRUS THAT CAUSES FILES IN REMOVBLE RIVE/PEN DRIVE/MEMORY CARD TO become shortcut. For this just download usbfix software here . Step 1:- UNRAR AND DOUBLE CLICK IT WILL  INSTALL ~~~~~~~~~~~~Plug in all your drive that are corrupted with virus ~~~~~~~~~~~~~~~~~ 2:- now first click on” research “button.~~~~~~~~~~~~~~~by RAAJ DUBEY~~~~~~~~~~~~~~~ ~~~~~~~~~~Be patient this step may take many time it will hang on 73 % for much time. Do not cancel here~~~~~~~~~~~~~~~~~~~~~`` 3:- now click on “deletion” button ~~~~~~~~~~usbfix window will close ~ now again double click on usbfix ico located at desktop~~~~~~~~~~~JINJAX TRICK ~~~~~~~~~~~~~~~~~~~` ~~~~~~~again it will scan and delete virus~~~~~~~~~~~~~~` 4:- now click on “lising” button t list all your files back in pd means all shortcut will be deleted and Original folder ,file will b...