1. 程式人生 > >JAVA 建立一個執行緒的三種方式

JAVA 建立一個執行緒的三種方式

  • 建立多執行緒-實現Runnable介面 建立類Battle,實現Runnable介面 啟動的時候,首先建立一個Battle物件,然後再根據該battle物件建立一個執行緒物件,並啟動   Battle battle1 = new Battle(gareen,teemo); new Thread(battle1).start();   battle1 物件實現了Runnable介面,所以有run方法,但是直接呼叫run方法,並不會啟動一個新的執行緒。 必須,藉助一個執行緒物件的start()方法,才會啟動一個新的執行緒。 所以,在建立Thread物件的時候,把battle1作為構造方法的引數傳遞進去,這個執行緒啟動的時候,就會去執行battle1.run()方法了。
    1. package multiplethread;
    2. import charactor.Hero;
    3. public class Battle implements Runnable{
    4. private Hero h1;
    5. private Hero h2;
    6. public Battle(Hero h1, Hero h2){
    7. this.h1 = h1;
    8. this.h2 = h2;
    9. }
    10. public void run(){
    11. while(!h2.isDead()){
    12. h1.attackHero(h2);
    13. }
    14. }
    15. }
    1. package multiplethread;
    2. import charactor.Hero;
    3. public class TestThread {
    4. public static void main(String[] args) {
    5. Hero gareen = new Hero();
    6. gareen.hp = 616;
    7. gareen.damage = 50;
    8. Hero teemo = new Hero();
    9. teemo.hp = 300;
    10. teemo.damage = 30;
    11. Hero bh = new Hero();
    12. bh.hp = 500;
    13. bh.damage = 65;
    14. Hero leesin = new Hero();
    15. leesin.hp = 455;
    16. leesin.damage = 80;
    17. Battle battle1 = new Battle(gareen,teemo);
    18. new Thread(battle1).start();
    19. Battle battle2 = new Battle(bh,leesin);
    20. new Thread(battle2).start();
    21. }
    22. }