Java线程强制执行和礼让执行

线程的强制执行

当满足某些条件时,某一个线程对象可以将资源一直独占,一直到线程执行结束

正常执行

public class TestThread {
	public static void main(String[] args) throws Exception {
		Thread thread = new Thread(() -> {
			for (int x = 0; x < 100; x++) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
			}
		}, "线程");
		thread.start();
		for (int x = 0; x < 100; x++) {
			Thread.sleep(100);
			System.out.println("main线程执行 " + "num = " + x);
		}
	}
}

结果如下

在这里插入图片描述

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

强制执行方法:public final void join() throws InterruptedException

public class TestThread {
	public static void main(String[] args) throws Exception {
		Thread mainThread = new Thread().currentThread();  //主线程
		Thread thread = new Thread(() -> {
			for (int x = 0; x < 100; x++) {
				if(x == 3) {
					try {
						mainThread.join();  //主线程执行
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
			}
		}, "线程");
		thread.start();   //子线程执行
		for (int x = 0; x < 100; x++) {
			Thread.sleep(100);
			System.out.println("main线程执行 " + "num = " + x);
		}
	}
}

结果如下

在这里插入图片描述
在这里插入图片描述

线程的礼让

线程的礼让是先将资源让出去让别的线程先执行,可以使用Thread中提供的方法,礼让执行的时候每调用一次yield()方法只会礼让一次当前资源

礼让方法:public static void yield()

礼让操作

public class TestThread {
	public static void main(String[] args) throws Exception {
		Thread thread = new Thread(() -> {
			for (int x = 0; x < 100; x++) {
				if(x % 3 == 0) {
					Thread.yield();
					System.out.println("线程礼让执行");
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
			}
		}, "线程");
		thread.start();   
		for (int x = 0; x < 100; x++) {
			Thread.sleep(100);
			System.out.println("main线程执行 " + "num = " + x);
		}
	}
}

结果如下(线程礼让后main线程执行)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值