关闭

线程面试题

283人阅读 评论(0) 收藏 举报

子线程循环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();

	}

}

 

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:312227次
    • 积分:8737
    • 等级:
    • 排名:第2257名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论