Java多线程基础六——sleep()方法的理解,执行顺序的两种不同情况案例(run 和 start 对sleep的不同反映)

2023-05-16

方法简单解释

sleep()方法的作用就是在指定的毫秒数内让当前“正在执行”的线程进入休眠状态,在这里这个“正在执行”的线程指的是this.currentThread()返回的线程
下面照例通过一些例子进行方法解释:在下面的测试运行结果重点看他们的输出的顺序

package MyThread;
public class mythread extends Thread{

  @Override
  public void run() {
	try {
		System.out.println("run threadName="+this.currentThread().getName()+"开始");
		Thread.sleep(2000);
		System.out.println("run threadName="+this.currentThread().getName()+"结束");
	}catch(InterruptedException e){
		e.printStackTrace();
	}
  }
}

run方法:

package test;
import MyThread.mythread;
public class Run1 {
	public static void main(String[] args) {
		mythread my=new mythread();
		System.out.println("开始  ="+System.currentTimeMillis());
		my.run();
		System.out.println("结束  ="+System.currentTimeMillis());
	}
}

运行结果:
在这里插入图片描述
在这里我们发现这个顺序上还是比较符合预期的
我们继续实验:将run变成start

package MyThread;

public class MyThread2 extends Thread{

	@Override
	public void run() {
		try {
			System.out.println("run threadName="+this.currentThread().getName()+"begin ="+System.currentTimeMillis());
			Thread.sleep(2000);
			System.out.println("run threadName="+this.currentThread().getName()+"end ="+System.currentTimeMillis());
		}catch(InterruptedException e){
			e.printStackTrace();	
		}
	}
}

run一run:

package test;
import MyThread.MyThread2;
public class Run2{
	public static void main(String[] args) {
		MyThread2 mythread=new MyThread2();
		System.out.println("begin ="+System.currentTimeMillis());
		mythread.start();
		System.out.println("end   ="+System.currentTimeMillis());
		
	}
	
}

运行结果:
在这里插入图片描述
在这里发现并没有符合我们的预期,在这里解释一下:由于main线程和MyThread2线程是异步执行的,所以首先打印的肯定是begin和end信息而后再去执行其他线程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java多线程基础六——sleep()方法的理解,执行顺序的两种不同情况案例(run 和 start 对sleep的不同反映) 的相关文章

随机推荐