Java多线程之Thread类


一、Thread类常用构造方法:

Thread(Runnable target, String name)    // 分配新的Thread对象,并给此线程起个名字
Thread(Runnable target)           // 只分配新的 Thread对象
Thread( String name)       // 只传任务名称。

二、常用方法:

void start()  // 此线程开始执行,Java虚拟机调用此线程的run方法

void run()  // 线程的任务

long getId()  //返回Thread的标识符

String getName()  // 返回此线程名称

int getPriority() // 返回此线程的优先级。

void setPriority(int newPriority) // 更改此线程的优先级
参数为静态常量:有三种
static int MAX_PRIORITY  //最大优先级
static int MIN_PRIORITY  // 最低优先级
static int NORM_PRIORITY // 默认优先级

static void sleep(long millis) // 使当前正在执行的线程休眠,参数为毫秒

static void sleep(long millis, int nanos) // 使当前正在执行的线程休眠,参数为毫秒+纳秒	

1.获取和设置线程的名称:

代码如下(示例):

public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        MyRunnable runnable = new MyRunnable();
        System.out.println(Thread.currentThread().getName());
        // 启动线程并给线程设置名称
        Thread thread = new Thread(runnable,"线程1"); 
        thread.start();
    }
    /**
     * @Description: 内部类
     * @Param: currentThread()  获取线程对象
     *         getName()  获取线程名称
     * @return:  
     */
    static class MyRunnable implements Runnable{
    
    
        @Override
        public void run() {
    
    
            System.out.println(Thread.currentThread().getName());
        }
    }
}

2.线程的休眠

public class Demo2 {
    
    
    // 线程的休眠,时间为 毫秒。
    public static void main(String[] args) throws InterruptedException {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}

总结

以上就是今天要讲的内容,本文仅仅简单介绍了Thread类常用的方法。

猜你喜欢

转载自blog.csdn.net/weixin_45663222/article/details/112150178