Java Multi-Threading

Source: Internet
Author: User
Tags thread class

Reference http://how2j.cn/k/thread/thread-start/353.html

Multithreading is at the same time, you can do multiple things.

There are 3 ways to create multithreading, namely, inheriting thread class, implementing Runnable interface, anonymous class

Threading Concepts

The first thing to understand is the difference between a process (Processor) and threads (thread)
process: Starting a LOL.exe is called a process. It then starts a DOTA.exe, which is called two processes.
Threads: threads are things that are done at the same time in the process, such as in Lol, there are many things to do at the same time, such as "Galen" Kill "Titus", while "bounty hunter" is also killing "blind Monk", which is achieved by multi-threading.

Creating multithreading-Inheriting thread classes

With multi-threading, the bounty hunter is attacking the blind monk at the same time that Galen attacks Titus.
Design a class Killthread inherit the thread, and override the Run method
Start threading Approach: Instantiate a Killthread object and call its start method
When the bounty hunter attacked the blind monk , Galen was attacking Titus.

Hero.java

 Public classHero { PublicString name;  Public floatHP;  Public intdamage;  Public voidAttackhero (Hero h) {Try{            //to indicate that the attack takes time, each attack pauses for 1000 millisecondsThread.Sleep ( +); }Catch(Exception e) {e.printstacktrace (); } h.hp-=damage; System. out. Format ("%s is attacking%s and the blood of%s has become%.0f%n", NAME,H.NAME,H.NAME,H.HP); if(H.isdead ()) System. out. println (H.name +"It's dead! "); }     PublicBoolean isdead () {return 0>=hp?true:false; }}

Killthread.java inherits the thread

 Public class Killthread extends Thread {    private  Hero H1;     Private Hero H2;      Public Killthread (Hero H1, Hero h2) {        this. H1 = H1;          this. H2 = h2;    }      Public void run () {        while ( !  H2.isdead ()) {            H1.attackhero (H2);     }}}

Testthread.java

 Public classTestthread { Public Static voidMain (string[] args) {Hero Gareen=NewHero (); Gareen.name="Galen"; GAREEN.HP=616; Gareen.damage= -; Hero Teemo=NewHero (); Teemo.name="Tim Mo"; TEEMO.HP= -; Teemo.damage= -; Hero BH=NewHero (); Bh.name="bounty Hunter"; BH.HP= -; Bh.damage= $; Hero Leesin=NewHero (); Leesin.name="Blind Monk"; LEESIN.HP=455; Leesin.damage= the; Killthread KillThread1=NewKillthread (Gareen,teemo);        Killthread1.start (); Killthread killThread2=NewKillthread (Bh,leesin);    Killthread2.start (); }}

Run results

Creating multithreading-Implementing the Runnable interface

Create class battle, implement Runnable interface
When started, a battle object is created first, then a thread object is created based on the battle object and started

New Battle (Gareen,teemo); New Thread (Battle1). Start ();

The Battle1 object implements the Runnable interface, so there is a run method, but calling the Run method directly does not start a new thread.
It is necessary to start a new thread by using the start () method of a Thread object.
So, when creating the thread object, Battle1 is passed in as a constructor parameter, and when the thread starts, it executes the Battle1.run () method.

Battle.java

Package multiplethread; Import charactor. Hero;  Public classBattle implements runnable{PrivateHero H1; PrivateHero H2;  PublicBattle (Hero H1, Hero h2) { This. H1 =H1;  This. H2 =H2; }      Public voidrun () { while(!H2.isdead ())        {H1.attackhero (H2); }    }}

TestThread. java

Package multiplethread; Import charactor. Hero;  Public classTestthread { Public Static voidMain (string[] args) {Hero Gareen=NewHero (); Gareen.name="Galen"; GAREEN.HP=616; Gareen.damage= -; Hero Teemo=NewHero (); Teemo.name="Tim Mo"; TEEMO.HP= -; Teemo.damage= -; Hero BH=NewHero (); Bh.name="bounty Hunter"; BH.HP= -; Bh.damage= $; Hero Leesin=NewHero (); Leesin.name="Blind Monk"; LEESIN.HP=455; Leesin.damage= the; Battle Battle1=NewBattle (Gareen,teemo); NewThread (Battle1). Start (); Battle Battle2=NewBattle (Bh,leesin); NewThread (Battle2). Start (); }     }
Create Multithreading-Anonymous classes

Using anonymous classes, inheriting thread, overriding the Run method, writing business code directly in the Run method
An advantage of an anonymous class is that it provides easy access to external local variables.
The premise is that the external local variables need to be declared final. (JDK7 will not be needed later)

TestThread. java

Package Multiplethread; Import Charactor.  Hero;  Public classTestthread { Public Static voidMain (string[] args) {Hero Gareen=NewHero (); Gareen.name="Galen"; GAREEN.HP=616; Gareen.damage= -; Hero Teemo=NewHero (); Teemo.name="Tim Mo"; TEEMO.HP= -; Teemo.damage= -; Hero BH=NewHero (); Bh.name="bounty Hunter"; BH.HP= -; Bh.damage= $; Hero Leesin=NewHero (); Leesin.name="Blind Monk"; LEESIN.HP=455; Leesin.damage= the; //Anonymous ClassThread t1=NewThread () { Public voidrun () {//external local variables used in anonymous classes, gareen Teemo, must be gareen declared as final Teemo//But after JDK7, it's not going to have to be final .                 while(!Teemo.isdead ())                {Gareen.attackhero (Teemo);                 }                          }        };                  T1.start (); Thread T2=NewThread () { Public voidrun () { while(!Leesin.isdead ())                {Bh.attackhero (Leesin);        }                          }        };             T2.start (); }      }
Three ways to create multithreading

Java Multi-Threading

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.