5.多线程基础1

1.启动一个线程

 创建多线程有三个方式

1.继承线程类

public class KillThread extends Thread{
    private Hero h1;
    private Hero h2;

    public KillThread(Hero h1, Hero h2){
        this.h1 = h1;
        this.h2 = h2;
    }
    @Override
    public void run(){
        while(!h2.isDead()){
            h1.attackHero(h2);
        }
    }
}

KillThread killThread1 = new KillThread(gareen,teemo);
killThread1.start();

2.实现runnable接口

package multiplethread;
 
import charactor.Hero;
 
public class Battle implements Runnable{
     
    private Hero h1;
    private Hero h2;
 
    public Battle(Hero h1, Hero h2){
        this.h1 = h1;
        this.h2 = h2;
    }
 
    public void run(){
        while(!h2.isDead()){
            h1.attackHero(h2);
        }
    }
}

        Battle battle2 = new Battle(bh,leesin);
        new Thread(battle2).start();

3.匿名类

          Thread t2= new Thread(){
            public void run(){
                while(!leesin.isDead()){
                    bh.attackHero(leesin);
                }              
            }
        };
        t2.start();

本质是重写run方法!!!!!!!!!!

2.常见线程方法

sleep    当前线程暂停

join     加入到当前线程中

setPriority  线程优先级

yield      临时暂停

setDaemon  守护线程

猜你喜欢

转载自www.cnblogs.com/yslu/p/10843473.html