线程休眠(Thread.Sleep)
- sleep(时间)指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
package www.bh.c.threadtest;
public class ThreadSleepTest implements Runnable {
private int ticket=10;
@Override
public void run() {
while (true){
if (ticket<=0){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
}
}
public static void main(String[] args) {
ThreadSleepTest threadSleepTest = new ThreadSleepTest();
new Thread(threadSleepTest,"你").start();
new Thread(threadSleepTest,"我").start();
new Thread(threadSleepTest,"他").start();
}
}
package www.bh.c.threadtest;
public class SleepTest2 {
public static void main(String[] args) {
SleepTest2 sleepTest2 = new SleepTest2();
sleepTest2.timeDown();
}
public void timeDown() {
int ten=10;
while (true){
if (ten<=0){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ten--);
}
}
}
package www.bh.c.threadtest
import java.text.SimpleDateFormat;
import java.util.Date;
public class SleepTest3 {
public static void main(String[] args) {
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date=new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
线程礼让(Thread.Yield)
- 线程礼让,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重写调度,礼让不一定成功!看cpu具体调度情况
package www.bh.c.threadtest;
public class YieldTest implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程结束执行");
}
public static void main(String[] args) {
YieldTest yieldTest = new YieldTest();
new Thread(yieldTest,"a").start();
new Thread(yieldTest,"b").start();
}
}
线程阻塞(Thread.Join)
- Join合并线程,待此方法执行完成后,再执行其他线程,此时其他线程阻塞
- 类似于插队
package www.bh.c.threadtest;
public class JoinTest implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("vip来了"+i);
}
}
public static void main(String[] args) {
JoinTest joinTest = new JoinTest();
Thread thread=new Thread(joinTest);
thread.start();
for (int i = 0; i < 500; i++) {
if (i==200){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("普通"+i);
}
}
}