sleep()方法///yield()方法///join()方法

线程休眠方法sleep()

  • 线程从运行状态到阻塞态
  • 线程休眠:让当前的线程暂缓执行,等到了预计时间后再恢复执行
  • 线程休眠会交出CPU,但是不会释放锁
class MyThread implements Runnable{
    public void run(){
        for(int i = 0;i < 10;i++){
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前线程:"+Thread.currentThread().getName()+",i="+i);
        }
    }
}
public class ticket{
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();

    }
}

线程让步方法yield()

  • 线程从运行态到就绪
  • 线程让步:暂停执行当前的线程对象,并执行其他线程
  • yield()方法会让当前线程交出CPU,同样不会释放锁
  • yield()方法无法控制具体交出CPU的时间
  • 只能让拥有相同优先级的线程有获取CPU的机会
class MyThread implements Runnable{
    public void run(){
        for(int i = 0;i<10;i++){
            Thread.yield();
            System.out.println("当前线程:"+Thread.currentThread().getName()+",i="+i);
        }
    }
}

public class ticket{
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();
    }
}

join()方法–等待其他线程终止

  • 运行到阻塞态
  • 等待该线程终止:如果在主线程中调用该方法时就会让主线程休眠,让调用该方法的线程run方法先执行完毕之后再开始执行主线程
class MyThread implements Runnable{
    @Override
    public void run() {
        try {
            System.out.println("主线程睡眠前的时间");
            ticket.printTime();
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName());
            System.out.println("睡眠结束的时间");
            ticket.printTime();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class ticket{
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        Thread thread = new Thread(mt,"子线程A");
        thread.start();
        System.out.println(Thread.currentThread().getName());
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("代码结束");
    }
    public static void printTime(){
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        System.out.println(time);
    }
}

猜你喜欢

转载自blog.csdn.net/WZL995/article/details/84200988