Thread中的方法
- 1.start():启动当前线程;调用当前线程的run()
- 2.run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
- 3.currentThread():静态方法,返回执行当前代码的线程
- 4.getName():获取当前线程的名字
- 5.setName():设置当前线程的名字,如h1.setName(“第一分线程”);
- 6.可以通过构造器来给线程命名,需在子类中重载一个带参构造器
- 7.yield():释放当前CPU的执行权
- 8.join():在线程A中,调用线程B的join()方法,此时线程A进入阻塞状态,直到线程B执行完以后线程A才结束阻塞状态:
- 9.stop():当执行此方法时强制结束此线程(这个方法已过时)
- 10.sleep(long millitime):让当前的线程“睡眠”millitime毫秒,在指定的millitime毫秒时间内,当前线程是阻塞状态
- 11.isAlive():返回boolean类型,判断此线程是否还存活
代码演示
class HThread extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
if(i%2==0){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
}
}
public HThread(String name){
super(name);
}
}
public class ThreadMethod419 {
public static void main(String[] args) throws InterruptedException {
HThread h1 = new HThread("Thread------1");
h1.start();
Thread.currentThread().setName("主线程");
for(int i=0;i<100;i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
if(i==20){
try{
h1.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
System.out.println(h1.isAlive());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52