On Java multithreading

Source: Internet
Author: User
Tags thread class

Multithreading is a concept proposed by Java, so what is a thread? Here are a few names that listen to something very similar: programs, threads, processes.

Program: A series of files stored on disk, including executables and non-executable files.

Process: In memory, each program will open a process.

Thread: The thread is the smallest execution unit of the process, and the thread is in the register, each thread consumes a certain amount of CPU resources and 512k to 1M of memory resources.

Multithreading: That is, the same program to open multiple threads is multithreaded.

What are the advantages of using multithreading? We all know that in Java, the code is executed one sentence at a time, the above code is not executed, the following code must wait until the above execution, it will be able to execute. If a program requires that different code be executed at the same time, the single thread is clearly unable to meet the requirements. In addition, because multithreading is executed together by several threads, it can greatly shorten the execution time of some code that requires a lot of repeated execution, for example, there is a catty meter to know how many tablets, if a person to count, do not know when to count. But if you send a few more people to count, you can greatly improve efficiency and save time. Real life is like this, the implementation of the program is more so. If a program is going to take a half minute to get the results, would you like to wait? Don't say half a minute, you don't have to wait a few seconds. So the role of multithreading is in this. Multithreading can improve the speed and execution efficiency of the program, can execute a piece of code at the same time, complete single-threaded things can not be done. Of course, things are double-sided, threading has its advantages, nature will also have flaws. As mentioned earlier, threads are consuming CPU and memory resources, and the CPU and memory resources are limited. Suppose this is the case where there are several threads that have to use the CPU, what should be done (asynchronous threads). The workaround of course is that the a thread that starters gets the CPU executes first, the other threads wait, the a thread finishes executing, frees the resources, and then the other threads are used again (thread synchronization). But this creates a new problem, if the a thread and the B thread execute at the same time, the a thread needs to wait for the resource release of the B thread to continue, and the B thread also needs the resource release of the A thread to continue, so that it gets stuck in a dead loop and no one will come out (the thread's deadlock). Of course, we do not need it because the thread is defective, but the advantage of the thread is that we want to use the thread.

There are two ways to use threads:

Inherit the thread class: The thread class implements the Runnable interface. Common methods are: the run () thread needs to be done in the Run method, sleep () the method that lets the thread hibernate, the parameter is the number of milliseconds, start () starts the thread's method, and start executes the Run method.

Implement the Runnable interface: what the run () thread needs to accomplish.

It is important to note that there is only one abstract run () method in the Runnable interface, it is not a method to start the thread, so the class that implements the Runnable interface wants to start the thread, and must instantiate a thread object. You can start a thread normally by calling the start method of the Thread object. I do not know whether people have such doubts: that is why you need to call the Start method class to start a thread, call the Run method directly do not? One thing you need to know to explain this is that if a program does not use threads, there will be no threads in the program. Look at the following code:

 Public class Test {    publicstaticvoid  main (string[] args) {        System.out.println ("Main method executed");        System.out.println (Thread.CurrentThread ());}    }

The result of this code output is this:

The Main method executes the
Thread[main,5,main]

This shows what, as long as there is a main method in our program, then the program will inevitably exist a thread. This means that Java's virtual opportunity automatically launches a thread for the main method. Threads in Java are scheduled by a Java virtual machine, and we cannot start the thread ourselves, so we need a start method to tell the virtual machine that we are going to start a thread. In other words, calling the Run method directly means that the Run method is called directly, and the thread is not started.

Here is an example of multithreading:

 PackageCom.cbs;ImportJava.awt.Color;ImportJava.awt.Graphics;ImportJava.awt.Graphics2D;Importjava.awt.RenderingHints;ImportJava.util.Random;ImportJavax.swing.JFrame;/*** Thread class, draw small ball *@authorCBS*/ Public classThreaddemoextendsThread {PrivateGraphics G; PrivateJFrame frame =NULL;  PublicThreaddemo () {} PublicGraphics Getg () {returnG; }     Public voidSETG (Graphics g) { This. G =G; }     PublicJFrame getframe () {returnframe; }     Public voidsetframe (JFrame frame) { This. frame =frame; }     PublicThreaddemo (JFrame frame, Graphics g) { This. frame =frame;  This. G =G;    System.out.println (frame); } Random R=NewRandom (); //Random ColorColor color =NewColor (R.nextint (255), R.nextint (255), R.nextint (255));  Public voidrun () {graphics2d g2d=(graphics2d) G;//G2d.setrenderinghint (renderinghints.key_antialiasing,//renderinghints.value_antialias_on);//                intSpeedx = 3;//the movement speed of the ball        intSpeedy = 3; intx =R.nextint (Frame.getwidth ()); inty =R.nextint (Frame.getheight ());  while(true) {            if(x < Frame.getwidth () && y <frame.getheight ())                {G2d.setcolor (color.white); G2d.filloval (x, Y,30, 30); X+=Speedx; Y+=speedy; //determine if you are hitting the border, or if you are bouncing the ball.                 if(X > Frame.getwidth () -20 && speedx > 0) {Speedx= -Speedx; } Else if(x < ten && Speedx < 0) Speedx= -Speedx; if(y >frame.getheight () -20 && speedy > 0) Speedy= -speedy; Else if(Y < x && Speedy < 0) Speedy= -speedy;                G2d.setcolor (Color.green); G2d.filloval (x, Y,30, 30); }            Try {                //Thread Hibernation                 This. Sleep (30); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }} PackageCom.cbs;/*** Main class, used to initialize an interface*/ImportJava.awt.Color;ImportJava.awt.Graphics;ImportJava.util.Random;ImportJavax.swing.JFrame; Public classDraw { Public Static voidMain (string[] args) {Draw d=NewDraw ();    D.showui (); }         Public voidShowUI () {JFrame JF=NewJFrame (); Jf.settitle ("Moving Point"); Jf.setsize (500,500); Jf.setdefaultcloseoperation (3); Jf.setlocationrelativeto (NULL);                        Jf.getcontentpane (). SetBackground (Color.White); Jf.setvisible (true); Graphics g=Jf.getgraphics (); Random R=NewRandom (); //randomly starting multiple threads         for(intI=0;i<=r.nextint (i++);) {Threaddemo T=NewThreaddemo ();            T.setframe (JF);            T.SETG (g);        T.start (); }    }    }
View Code

After running is a few balls in the interface everywhere bump.

PS: A bit small bug, I still do not know how.

On Java multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.