线程面试题

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

 

使用Object.wait()和Object.notify()方法实现等待和唤醒功能,实现多线程之间共享数据

package hb.threadcomunicate;

public class SynThread {

	boolean isSub = true;
	
	public synchronized void sub(int loop) {
		while(!isSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("sub thread : " + i + ";loop " + loop);
		}
		isSub = false;
		this.notify();
	}

	public synchronized void main(int loop) {
		while(isSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("main thread : " + i + ";loop " + loop);
		}
		isSub = true;
		this.notify();
	}

}

 

package hb.threadcomunicate;

public class ThreadCommunicate {

	public static void main(String[] args) {

		final SynThread synThread = new SynThread();

		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					synThread.sub(i);
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					synThread.main(i);
				}
			}
		}).start();

	}

}

 

 

阅读更多
上一篇多个线程之间共享数据
下一篇Eclipse 重构变量(名) 快捷键
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭