子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次

本文探讨了一个线程面试问题:如何实现子线程循环10次,接着主线程循环100次,并在两者间交替进行,总共重复50次。分析了代码修改后的可行性及其原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近经常为公司面试新人,问了一个简单的线程问题,许多培训机构也都出过这种练习题,题目如标题


package thread;
/**
 * 线程类
 * @author  zy
 *
 */
public class ExecutorThread{
	/**
	 * 标志子线程调用方法是否被调用
	 */
	private boolean mainIsRunning = false;
	
	/**
	 * 子线程调用方法
	 */
	public synchronized void sub(){
		
		while(mainIsRunning){//如果子线程方法没被调用,即调用了主线程执行
			//等待别的线程使用
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i = 0 ;i<10;i++){
			System.out.println("sub:" + i);
		}
		
		mainIsRunning = true;
		//唤醒别的在等待的线程
		this.notify();
		
	}
	
	/**
	 * 主线程调用方法
	 */
	public synchronized void main(){
		while(!mainIsRunning){//如果主线程没被调用,即子线程执行
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for(int i = 0 ;i<100;i++){
			System.out.println("main:" + i);
		}
		mainIsRunning = false;
		this.notify();
		
	}
}

package thread;

public class ExecutorThreadTest {
	public static void main(String[] args) {
		final ExecutorThread thread = new ExecutorThread();
		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					System.out.println("sub is " + i + "  count");
					thread.sub();
				}
			}

		}).start();

		for (int i = 0; i < 50; i++) {
			System.out.println("main is " + i + "  count");
			thread.main();
		}
	}
}

能运行通过


试问,如果我把代码修改成这样还能正常运行么?为什么

package thread;
/**
 * 线程类
 * @author  zy
 *
 */
public class ExecutorThread{
	/**
	 * 标志子线程调用方法是否被调用
	 */
	private boolean mainIsRunning = false;
	
	/**
	 * 子线程调用方法
	 */
	public synchronized void sub(){
		
		for(int i = 0 ;i<10;i++){
			System.out.println("sub:" + i);
		}
		
		mainIsRunning = true;
		//唤醒别的在等待的线程
		this.notify();
		try {
			this.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 主线程调用方法
	 */
	public synchronized void main(){
		for(int i = 0 ;i<100;i++){
			System.out.println("main:" + i);
		}
		mainIsRunning = false;
		this.notify();
		try {
			this.wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值