Java Thread.yield()方法(demo)

mac2022-06-30  80

Thread.yield()方法

复习多线程时,想敲一个demo来看下Thread的具体几个方法,其中yield方法,按自己理解敲一个demo,相比与网上其他的,感觉更好理解,且可以很好地体现"礼让"

示例

public class MyClass { volatile static long currTime = 0; public static void main(String[] args) { //此对象作为锁 MyClass myClass = new MyClass(); System.out.println("让时间短的先走"); Thread thread1 = new Thread(new Runnable() { @Override public synchronized void run() { long random = (long) (Math.random() * 1000); System.out.println("线程1耗时:" + random); // 判断是否礼让--礼让 if (currTime < random) { currTime = random; Thread.yield(); System.out.println("线程1礼让"); } synchronized (myClass) { try { // System.out.println("线程1:running"); Thread.sleep(random); System.out.println("线程1:end"); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { long random = (long) (Math.random() * 1000); System.out.println("线程2耗时:" + random); // 判断是否礼让--礼让 if (currTime < random) { currTime = random; Thread.yield(); System.out.println("线程2礼让"); } synchronized (myClass) { try { // System.out.println("线程2:running"); Thread.sleep(random); System.out.println("线程2:end"); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread1.start(); thread2.start(); } }

补充:volatile 是一个关键字,修饰后每次读取的都是最新值,一个线程修改,另一个会马上察觉到

很简单的一个demo,就是两个线程共用一个对象锁,所以两个线程执行时必须抢占使用,我的想法就是加入yield()方法,让sleep短的那个线程先执行

结果

最新回复(0)