1.线程的一些常用方法
package javastudy01;
class MyThread extends Thread {
//重写Run方法
public void run(){
//1.获取当前线程的名字
System.out.println(this.getName()+"我是一个线程.");
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
//2.Thread.currentThread() 获取当前线程
System.out.println( Thread.currentThread().getName());
}
}
运行结果
package javastudy01;
class MyThread extends Thread {
public void run(){
//设置线程名方法1
this.setName("胡博士");
System.out.println(this.getName()+":我是一个线程.");
}
public static void main(String[] args) {
MyThread mt = new MyThread();
//设置名字方法2
mt.setName("clare");
mt.start();
}
}
并且在使用This的同时再使用方法二,方法二的命名不起作用
休眠线程:
package javastudy01;
public class sleep {
//倒计时程序
public static void main(String[] args) throws InterruptedException {
for(int i=10;i>=0;i--){
Thread.sleep(1000); //此处因为是静态方法,所以Thread类名可以直接调用
System.out.println(i);
}
}
}
运行结果
守护线程(重点)
正常情况下一下程序t1执行30次,t2执行50次 加上守护线程后会有变化
守护线程不会单独执行,在其他非守护线程都执行结束后,它也会自动退出不再执行
package javastudy01;
public class setDaemon {
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run(){
for(int i=0; i<30;i++){
System.out.println(this.getName() +" : "+ i);
}
}
};
Thread t2 = new Thread(){
public void run(){
for(int i=0; i<50;i++){
System.out.println(this.getName() +" : "+ i);
}
}
};
t2.setDaemon(true);
t1.start();
t2.start();
}
}
运行结果
加入线程
join()当前线程暂定,待指定的线程执行结束后,再继续
t.join(); 相当于给t插队
join(int) 等待指定毫秒后继续
礼让线程
yield 让出CPU给其他线程
2.线程的优先级设置
Thread.setPriority()
1-10 参数 默认值5
优先级大的线程执行次数多(是执行次数多,不是仅让它先执行)