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

3g what it is

Definition of 3G: 3G is the third generation of wireless technologies. It comes with enhancements over previous wireless technologies, like high-speed transmission, advanced multimedia access and global roaming. 3G is mostly used with mobile phones and handsets as a means to connect the phone to the Internet or other IP networks in order to make voice and video calls, to download and upload data and to surf the net. How is 3G Better?: 3G has the following enhancements over 2.5G and previous networks: Several times higher data speed; Enhanced audio and video streaming; Video-conferencing support; Web and WAP browsing at higher speeds; IPTV (TV through the Internet) support. 3G Technical Specifications: The transfer rate for 3G networks is between 128 and 144 kbps (kilobits per second) for devices that are moving fast and 384 kbps for slow ones(like for pedestrians). For fixed wireless LANs, the speed goes beyond 2 Mbps. 3G is a set of technologies and stand

Dragon Age: Inquisition Digital Deluxe Edition + All DLCs (torrent) Repack Size: 20.1~23.9 GB

Brief : Dragon Age: Inquisition  is an  action role-playing video game  developed by  Bioware Edmonton  and published by  Electronic Arts . The third major game in the  Dragon Age  franchise,  Dragon Age: Inquisition  is the sequel to  Dragon Age: Origins  and  Dragon Age II . The game was released worldwide in November 2014 for  Microsoft Windows ,  PlayStation 3 ,  PlayStation 4 ,  Xbox 360 , and  Xbox One . Repack Size: 20.1~23.9 GB 

How to Create Your Own Customized Run Commands

The Run command on Microsoft Windows operating system allows you to directly open an application or document with just a single command instead of navigating to it’s location and double-clicking the executable icon. However, it only works for some of the inbuilt Windows programs such as Command prompt (cmd), Calculator (calc) etc. So, have you ever wondered how to create your own customized Run commands for accessing your favorite programs, files and folders? Well, read on to find out the answer. Creating the Customized Run Command: Let me take up an example of how to create a customized run command for opening the Internet explorer. Once you create this command, you should be able to open the Internet explorer just by typing ie in the Run dialog box. Here is how you can do that. Right-click on your Desktop and select New -> Shortcut. You will see a “Create Shortcut” Dialog box as shown below Click on “Browse”, navigate to: Program Files -> Internet Explorer from y

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 your blog. In this tutorial, I

6 Ways to Hack or deface Websites Online

Hello friends , today i will explain all the methods that are being used to hack a website or websites database. This is the first part of the hacking websites tutorial where i will explain in brief all methods for hacking or defacing websites. Today I will give you the overview and in later tutorials we will discuss them one by one with practical examples. So guys get ready for first part of Hacking websites class.... Don't worry i will also tell you how to protect your websites from these attacks and other methods like hardening of SQL and hardening of web servers and key knowledge about CHMOD rights that what thing should be give what rights... Note : This post is only for Educational Purpose only. What are basic things you should know before website hacking? First of all everything is optional as i will start from very scratch. But you need atleast basic knowledge of following things.. 1. Basics of HTML, SQL, PHP. 2. Basic knowledge of Javascript. 3. Basic knowled

What Are Search Engine Spiders?

A spider, also known as a robot or a crawler, is actually just a program that follows, or "crawls", links throughout the Internet, grabbing content from sites and adding it to search engine indexes. Spiders only can follow links from one page to another and from one site to another. That is the primary reason why links to your site (inbound links) are so important. Links to your website from other websites will give the search engine spiders more "food" to chew on. The more times they find links to your site, the more times they will stop by and visit. Google especially relies on its spiders to create their vast index of listings. Spiders find Web pages by following links from other Web pages, but you can also submit your Web pages directly to a search engine or directory and request a visit by their spider. In fact, it's a good idea to manually submit your site to a human-edited directory such as Yahoo, and usually spiders from other search e

How to Show JavaScript or HTML Code on Blogger Blog Posts

How to Display Code on Blogger Posts In order to display codes on blogger blog you should convert them to escaped characters and show them under the HTML tag   pre  as shown below. code in escaped characters Now let us check how to convert a script in to escaped form.  How to Convert HTML/Java Script code in to Escaped Characters You can simply parse a script in to escaped format by following the changes given below. <  must be changed with   < >  should be changed with  > “  should be changed with  " In case if the script is too big to convert manually, you can use any tools which convert a Java script or HTML script in to escaped version. The following links will help you to convert normal HTML and JavaScript codes in to Escaped Characters automatically.  http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php http://codeformatter.blogspot.in/2009/06/about-code-formatter.html Showing JavaScript and HTML codes in plain text

12 Tips to Maintain a Virus Free Computer

1. Email is one of the common ways by which your computer can catch a virus . So it is always recommended to stay away from SPAM. Open only those emails that has it’s origin from a trusted source such as those which comes from your contact list. If you are using your own private email host (other than gmail, yahoo, hotmail etc.) " then it is highly recommended that you use a good anti-spam software. And finally NEVER click on any links in the emails that comes from untrusted sources. 2. USB thumb/pen drives is another common way by which viruses spread rapidly." So it is always a good habit to perform a virus scan before copying any data onto your computer. NEVER double-click the pen drive to open it. Instead right-click on it and select the option “open”. This is a safe way to open a pen drive. 3. Be careful about using MS Outlook. Outlook is more susceptible to worms than other e-mail programs, unless you have efficient Anti-Virus programs running. Use Pegasus

8 Tools to Track Registry and File Changes by installing a software

1.  Regshot unicode Regshot is a long running utility that can quickly take a before and after snapshot of the system registry. Also in the more recent unicode version it’s gained the ability to monitor for file changes using CRC32 and MD5 file checksums although this function is turned off by default and you have to go to File -> Options -> Common Options -> and tick “Check files in the specified folders” to enable it. Only the Windows folder is entered into the list of watched folders so you have to enter any others yourself through the Folders tab. This version also added the Connect to remote registry option. Regshot is very much a “hands on” utility and is more for experienced or advanced users to quickly check for system changes between two different points in time. Simply create the 1st shot, install the software or run the program you want to watch, and then press 2nd shot. After comparing the differences in the 1st and 2nd shots, it will open an HTML log in y