2016.8.4
实现线程的两种方式
1.直接继承Thread
class Download extends Thread {
public void run(){
for(int i=0;i<=100;i++){
System.out.println("正在下载片子:"+i+"%");
}
}
}
Thread download = new Download();
2.实现Runnable接口
class PlayLOL implements Runnable{
public void run() {
for(int i=0;i<=100;i++){
System.out.println("正在玩LOL,已经补了"+i+"个小兵");
}
}
}
Thread playlol = new Thread(new PlayLOL());
线程的方法
(1)
线程进入就绪状态,等待调度
download.start();
(2)
线程休眠,休眠500毫秒
Thread.sleep(500);
(3)
join()
先执行完调用join的线程,再执行这条语句之后之后的代码
join(long millis)
先执行100毫秒调用join的线程,再执行这条语句之后的代码
download.join();
download.join(100);
(4)
setDaemon(boolean on)守护线程,调用本线程的线程结束,就结束本线程
main方法运行结束,就结束download线程,main就是主线程
public static void main(String[] args){
Thread download = new Download();
download.setDaemon(true);
}
(5)
设置和获取线程名字
download.setName("下载")
download.getName()
(6)
设置和获取线程优先级
download.setPriority(10)
download.getPriority()