线程中的几个方法解释

sleep(long millis);
// 当前线程 睡眠多少毫秒
sleep(long millis, int nanos)
// 当前线程睡眠多少毫秒+ 多少纳秒
//这两个方法均是static 关键字修饰的方法 静态方法 在线程中直接调用Thread.sleep(xxx) 即可,阻塞的是当前线程

yield()方法
理论上,yield意味着放手,放弃,投降。一个调用yield()方法的线程告诉虚拟机它礼让其他线程占用自己的位置。这表明该线程没有在做一些紧急的事情。注意,这仅是一个暗示,并不能保证不会产生任何影响。
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint
*/
public static native void yield();
必须理解以下几个概念:
Yield是一个静态的原生(native)方法
Yield告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
Yield不能保证使得当前正在运行的线程迅速转换到可运行的状态
它仅能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态

join()
我的理解是 从多线程之间的并行转化为串行

/**
* Waits for this thread to die.
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* interrupted status of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
源码说明:等到当前的线程挂掉 才会释放它的资源,抛出异常说的是如果有任何别的线程打断此线程 将会抛出异常并清理退出。
private static class MyThread extends Thread{
private Thread thread;
public MyThread(String str, Thread thread){
super(str);
this.thread = thread;
}

    @Override
    public void run() {
        for(int i = 0 ; i<30 ;i++ ){
            System.out.println(this.getName() + i);
            if(i == 15 && thread != null){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}


public static void main(String args[]){
    Thread t2 = new MyThread("dc" ,null);
    Thread t1 = new MyThread("qf", t2);

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

}

输出顺序:

qf0
qf1
qf2
qf3
qf4
qf5
qf6
qf7
qf8
qf9
qf10
qf11
qf12
qf13
qf14
qf15
dc0
dc1
dc2
dc3
dc4
dc5
dc6
dc7
dc8
dc9
dc10
dc11
dc12
dc13
dc14
dc15
dc16
dc17
dc18
dc19
dc20
dc21
dc22
dc23
dc24
dc25
dc26
dc27
dc28
dc29
qf16
qf17
qf18
qf19
qf20
qf21
qf22
qf23
qf24
qf25
qf26
qf27
qf28
qf29

从并行的转为串行

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值