线程中常用的方法

一、获取当前线程

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

结果:

 Thread[main,5,main]

 二、线程的名字

public final synchronized void setName(String name) {
    checkAccess();
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;
    if (threadStatus != 0) {
        setNativeName(name);
    }
}

/**
 * Returns this thread's name.
 *
 * @return  this thread's name.
 * @see     #setName(String)
 */
public final String getName() {
    return name;
}
 public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        thread.setName("线程的名字");
        thread.start();

    }

 三、线程的优先级

cpu调度线程的优先级

有1 - 10 这10个级别。

 public final static int MIN_PRIORITY = 1;

/**
  * The default priority that is assigned to a thread.
  */
 public final static int NORM_PRIORITY = 5;

 /**
  * The maximum priority that a thread can have.
  */
 public final static int MAX_PRIORITY = 10;
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("t1: "+ i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("t2: "+i);
                }
            }
        });

        t2.setPriority(Thread.MAX_PRIORITY);
        t1.setPriority(Thread.MIN_PRIORITY);

        t1.start();
        t2.start();

    }

四、线程的礼让

通过Thread类中的静态方法 yield()来实现

public static native void yield();
public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    if(i == 5){
                        Thread.yield();
                    }

                    System.out.println("t1: " + i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("t2: " + i);
                }
            }
        });

        t1.start();
        t2.start();
    }

注: yield() 方法释放了cpu,但是不释放锁资源

五、线程的休眠

通过Thread类中的静态方法sleep() 实现的

// 使线程转入 TIME WAITING 的状态
public static native void sleep(long millis) throws InterruptedException;
// JDK 8中是这样的
// 传入两个参数,一个是毫秒 mills ,另一个是纳秒 nanos
public static void sleep(long millis, int nanos) throws InterruptedException {
    // mills的健壮性考虑 
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }
    // nanos的健壮性判断
    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }
    // 如果纳秒的值大于 0.5 毫秒 或者 纳秒值不为0,但是毫秒值为0,那么 mills ++
    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }
    // 睡眠以上时间
    sleep(millis);
}

 // JDK 17

public static void sleep(long millis, int nanos) throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos > 0 && millis < Long.MAX_VALUE) {
        millis++;
    }
    sleep(millis);
}
 public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println("t1: "+i);
                    if(i == 15){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        t1.start();
    }

注:sleep() 方法不释放锁,释放cpu

六、线程的强占

join 方法 释放锁,抢占CPU

1. 如果在main线程中调用了t1.join(),那么main线程会进入到等待状态,需要等待t1线程全部执行完毕,在恢复到就绪状态等待CPU调度。

2. 如果在main线程中调用了t1.join(2000),那么main线程会进入到等待状态,需要等待t1执行2s后,在恢复到就绪状态等待CPU调度。如果在等待期间,t1已经结束了,那么main线程自动变为就绪状态等待CPU调度。

public final void join() throws InterruptedException {
    join(0);
}
public final synchronized void join(long millis)
throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

 public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("t1: "+i);
                }
            }
        });

        t1.start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(i == 3){
                try {
//                    t1.join(2000);
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

七、守护线程

当主线程(默认是非守护线程)结束后,看JVM是否有守护线程,若无,则JVM直接停止。

 public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("t1: " + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        // 设置为守护线程
        t1.setDaemon(true);
        t1.start();
    }

八、线程的等待和唤醒

可以让获取synchronized锁资源的线程通过wait方法进去到锁的等待池,并且会释放锁资源

可以让获取synchronized锁资源的线程,通过notify或者notifyAll方法,将等待池中的线程唤醒,添加到锁池

notify随机的唤醒等待池中的一个线程到锁池

notifyAll将等待池中的全部线程都唤醒,并且添加到锁池

在调用wait方法和notify以及norifyAll方法时,必须在synchronized修饰的代码块或者方法内部才可以,因为要操作基于某个对象的锁的信息维护。

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                sync();
            }
        },"t1");

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                sync();
            }
        },"t2");

        t1.start();
        t2.start();
        Thread.sleep(12000);

        synchronized (ThreadName.class){
            ThreadName.class.notifyAll();
        }

    }

    public static synchronized void sync() {

        try {
            for (int i = 0; i < 10; i++) {
                if (i == 5) {
                    ThreadName.class.wait();
                }
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName());
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值