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

13 websites to register your free domain

Register your Free Domain Now!! 1)  .tk Dot TK is a FREE domain registry for websites on the Internet. It has exactly the same power as other domain extensions, but it’s free! Because it’s free, millions of others have been using .TK domains since 2001 – which makes .TK powerful and very recognizable.  Your website will be like www.yourdomainname.tk . It is free for 1 year. It’s a ccTLD domain whixh having the abbreviation  Tokelau. To create a .tk domain, Visit   www.dot.tk 2) co.cc Co.cc is completely free domain which is mostly used by blogspot bloggers because of it’s easy to use DNS system. Creating a co.cc for blogger is simple ( for instructions- “click here”). Your website will be like www.yourdomainname.co.cc . To create a .co.cc domain, visit www.co.cc 3)   co.nr co.nr is too like co.cc. Your website will be like  www.yourdomainname.co.nr . You can add it for blogger also.. To create a .co.cc domain, vi...

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...

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...

How to Bypass Right Click Block on Any Website

In order to block the right-click activity, most websites make use of JavaScript which is one of the popular scripting languages used to enhance functionality, improve user experience and provide rich interactive features. In addition to this, it can also be used to strengthen the website’s security by adding some of the simple security features such as  disabling right-click ,  protecting images ,  hiding or masking parts of a web page  and so on. How JavaScript Works? Before you proceed to the next part which tells you how to disable the JavaScript functionality and bypass any of the restrictions imposed by it, it would be worthwhile for you to take up a minute to understand how JavaScript works. JavaScript is a client side scripting language (in most cases), which means when loaded it runs from your own web browser. Most modern browsers including IE, Firefox, Chrome and others support JavaScript so that they can interpret the code and carry out action...

[ FREE ][ more than 15 gb for free ] Offcloud vs Bitport vs Seedr :which is best among three to direct download from torrent to cloud storages like google drive ,one drive ,dropbox etc.

Offcloud : [RECOMMENDED BY ME] [AS OF 17-july-2017] Offcloud is a little different from the rest of the providers we’ve looked at, as it isn’t focused on downloading torrents. The company markets itself as “a simple, elegant and intuitive  SaaS  to retrieve any data from the cloud.” We were surprised at the amount of different sources Offcloud supports for downloading, and it even has a ticket box that allows users to suggest new sites to support.  pros: best part you can direct download to your cloud storage like google drive , mega.NZ,one drive ,Dropbox,etc.. Cons: only 3 links permitted to download over free account ..that limit is per months .. you can buy a premium account to bypass this .............. else you can also use a fake email generator and add a remote account to cloud download bypasssing above limit.. Note that Off-cloud doesn’t intend to act as a “seedbox,” which is a server used to boost a user’s ration on private trackers by perpetua...

Facebook's First Layout

... More about fb: Facebook paid a whooping $8.5 Million to buy "Fb.com" domain!! So next time instead of typing "facebook.com" you can just type in "Fb.com" to save time!! Facebook acquired the domain sometime last year from the American Farm Bureau Federation, which uses fb.org as its primary domain. At its annual meeting in Atlanta, the non-profit revealed that it earned $8.5 million on the sale of fb.com The last high-profile domain purchase by Facebook was for Facebook.com, all the way back when it was known as TheFacebook. The company paid $200,000 in August 2005 to acquire the domain, 42.5 times less than what Facebook spent to acquire fb.com. While the Facebook.com purchase was expensive for the company back then, it’s an investment that has clearly paid off. The company is obviously hoping that fb.com will also pay off. source: https://en.wikipedia.org/wiki/File:Original-facebook.jpg

Android :Edittext Format space after Each 4 digit/Character

Replace EditText with your EditText Variable 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 EditText . addTextChangedListener ( new TextWatcher () { byte count1 = 0 ; byte count2 = 0 ; @Override public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { count1 = ( byte ) s . length (); } @Override public void onTextChanged ( CharSequence s , int start , int before , int count ) { count2 = ( byte ) s . length (); } @Override public void afterTextChanged ( Editable s ) { String initial = EditText . getText (). toString (); ...

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...

C++ Program to implement File Handling by using ifstream & ofstream -2

Write a paragraph (At least 2 lines of sentences) in a file. Read the same file in three different ways –   i) Reverse the whole paragraph.  ii) Line by Line Reverses the whole para. iii) Break the paragraph into two equal halves. Reverse the second half of the paragraph. #include #include <fstream.h> #include <conio.h> void main(){     char para[500], ln[80];     int len, i, half;     clrscr();     cout<<"\n Enter a Paragraph (Quit by ^Z):-";     cout<<"\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";     cin.getline(para, 500, '^Z');     len = strlen(para);     ofstream fout;     fout.open("para.txt", ios::out);     fout.write((char *) &para, len);     fout.close();     ifstream fin;     cout<<"\n Reverse the Whole Paragraph:-";     cout<<"\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~";     fin.open...

Batch file to C++ souce code generator ...

Batch file to C++ souce code generator ... Well this project was made upon CODEBLOCK using c++ HERE IS THE SOURCE CODE: download it as .cpp form by clicking here.. mirror 1                                                   mirror 2. One drive if YOu want the exe file only then click here (500 KB) Mirror 1. MULTCLOUD  FOR PASSWORD TO THIS SITE VISIT THE FOLLOWING LINK OR SUMBIT THE FORM BELOW  >>> LINK :   https://goo.gl/forms/DiQHvEjfavsaU18U2                              or Loading...