码迷,mamicode.com
首页 > 编程语言 > 详细

5.多线程基础1

时间:2019-05-10 12:54:32      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:基础   tle   sde   sleep   临时   private   tee   daemon   priority   

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  守护线程

5.多线程基础1

标签:基础   tle   sde   sleep   临时   private   tee   daemon   priority   

原文地址:https://www.cnblogs.com/yslu/p/10843473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!