Java多线程:线程强制运行和线程礼让

所谓线程强制执行指的是当满足于某些条件之后,某一个线程对象将可以一直独占资源,一直到该线程的程序执行结束。

范例:观察一个没有强制执行的程序

public class Main{
	
	public static void main(String args[]) {
		Runnable run = ()->{
			for(int i = 0; i < 100; i++) {
//				try {
//					Thread.sleep(100);
//				}
//				catch(InterruptedException e){
//					e.printStackTrace();
//				}
				System.out.println(Thread.currentThread().getName() + "执行、i = " + i);
			}
		};
		Thread thread = new Thread(run, "测试线程");
		thread.start();
		for(int i = 0; i < 100; i++) {
			System.out.println("主线程");
		}
	}
}

没有强制执行,两个线程一直在互相抢资源。

如果希望主线程独占资源,那么就可以用Thread里面的方法强制执行

  • 强制执行:public final void join​() throws InterruptedException;

在进行线程强制执行的时候一定要获取强制执行线程对象之后才可以调用join()

线程的礼让指的是先将资源让出去让别的线程先执行。线程的礼让可以使用Thread中提供的方法

  • 礼让:public static void yield​();

范例:使用礼让操作

public class Main{
	
	public static void main(String args[]) {
		Thread mainThread = Thread.currentThread();
		Runnable run = ()->{
			for(int i = 0; i < 100; i++) {
				
				System.out.println(Thread.currentThread().getName() + "执行、i = " + i);
			}
		};
		Thread thread = new Thread(run, "测试线程");
		thread.start();
		for(int i = 0; i < 100; i++) {
			if(i % 3 == 0) {
				System.out.println("线程礼让了");
				Thread.yield();	// 线程礼让
			}
			System.out.println("主线程");
		}
	}
}

礼让执行的时候每一次调用yield()方法都只会礼让一次当前的资源。

发布了238 篇原创文章 · 获赞 104 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/hpu2022/article/details/103326855