34. Thread类的常用方法

1.构造方法

Thread()         分配新的 Thread 对象。

Thread(String name)    分配新的 Thread 对象并指定线程名字

2.方法

1)setName(String name)   设置线程的名字

public final void setName(String name)

2)getName()        获取线程名字

public final String getName()

public static void main(String[] args) {
        Thread thread = new Thread("狗娃");
        System.out.println(thread.getName());;
        thread.setName("张三");
        System.out.println(thread.getName());;
}

 

扫描二维码关注公众号,回复: 81875 查看本文章

3)sleep()         指定线程睡眠的时间,单位毫秒(注意:谁执行了sleep代码,谁睡眠,并不是谁调用了sleep方法谁睡眠)

public static void sleep(long millis,int nanos)

                throws InterruptedException

class sonThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是自定义线程");
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        
        sonThread sonthread = new sonThread();
        sonthread.start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < 100; i++) {
            System.out.println("我是main线程");
        }
    }
}

注意:sleep代码是main线程执行的,所以main线程随眠200毫秒

4)currentThread()          返回执行此代码的对象(注意:跟sleep一样是执行此代码,而不是调用)

public static Thread currentThread()
public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());    
}

5)getPriority()         返回当前线程对象的优先级(默认为5,优先级在1-10之间)

6)setPriority()         设置当前线程对象的优先级(默认为5,优先级在1-10之间)

public static void main(String[] args) {
        Thread thread = new Thread("狗娃");
        System.out.println("默认的优先级是:"+thread.getPriority());
        thread.setPriority(7);
        System.out.println("现在的优先级是:"+thread.getPriority());
}

猜你喜欢

转载自www.cnblogs.com/zjdbk/p/8964319.html