java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用

run(), start(), join(), yield(), sleep()

这些是多线程中常用到的方法.

run(): 每个Thread中需要实现的方法, 如果直接调用的话, 会是和单线程一样的效果, 要另起线程需要使用start().

start(): 新起线程调用run(). 主线程不等待直接往下执行

join(): 如果有一个Thread a, 在a.start()后面(可以使用thread.isAlive()判断). 使用a.join() 可以使主线程等待a执行完. 如果同时有多个线程a, b, c, 而d需要等abc执行完后才能执行, 可以在d start之前使用a.join, b.join, c.join, 也可以把a, b, c的start放到d的run方法里面, 使用a.join, b.join, c.join, 可以用参数设置timeout时间

class JoiningThread extends Thread {

// NOTE: UNTESTED!

private String name;

private Thread nextThread;

public JoiningThread(String name) {

this(name, null);

}

public JoiningThread(String name, Thread other) {

this.name = name;

this.nextThread = other;

}

public String getName() {

return name;

}

@Override

public void run() {

System.out.println("Hello I'm thread ".concat(getName()));

if (nextThread != null) {

while(nextThread.isAlive()) {

try {

nextThread.join();

} catch (InterruptedException e) {

// ignore this

}

}

}

System.out.println("I'm finished ".concat(getName()));

}

}

使用的时候

public static void main(String[] args) {

Thread d = WaitingThread("d");

Thread c = WaitingThread("c", d);

Thread b = WaitingThread("b", c);

Thread a = WaitingThread("a", b);

a.start();

b.start();

c.start();

d.start();

try {

a.join();

} catch (InterruptedException e) {}

}

yield(): 没发现有什么特别, 似乎是可以保证不同优先级的线程不会抢先运行

sleep(): 需要时间作为参数, 可以被interrupt.

wait() and notify(): 和join()的区别是, wait需要额外的notify来终止, 上面的类可以改写为

class WaitingThread extends Thread {

// NOTE: UNTESTED!

private Thread previousThread;

private String name;

public WaitingThread(String name) {

this(name, null);

}

public WaitingThread(String name, Thread other) {

this.name = name;

this.previousThread = other;

}

public String getName() {

return name;

}

@Override

public void run() {

System.out.println("Hello I'm thread ".concat(getName()));

// Do other things if required

// Wait to be woken up

while(true) {

synchronized(this) {

try {

wait();

break;

} catch (InterruptedException e) {

// ignore this

}

}

}

System.out.println("I'm finished ".concat(getName()));

// Wake up the previous thread

if (previousThread != null) {

synchronized(previousThread) {

previousThread.notify();

}

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值