zoukankan      html  css  js  c++  java
  • 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());;
    }

     

    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());
    }

  • 相关阅读:
    使用命令行工具创建.Net Core应用程序
    WinForm--DataGridView复制单元格数据
    WinForm--DataGridView导出数据到CSV文件
    进程和线程(线程是轻量级进程)(下)
    进程和线程(线程是轻量级进程)(中)
    C# 泛型(Generic)
    C# 事件(Event)
    C# 委托(Delegate)
    C# 反射
    C# 程序集(Assembly)
  • 原文地址:https://www.cnblogs.com/zjdbk/p/8964319.html
Copyright © 2011-2022 走看看