java的多线程编程

    要求:子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,
接着再回到主线程又循环100,如此循环50次,请写出程序。


    我的程序如下:
public class MainThread extends Thread {
	private Object lock;
	private int num;
	private int limit;

	public MainThread(Object lock, int limit) {
		this.lock = lock;
		this.limit = limit;
	}

	public static void main(String[] args) {
		Object lock = new Object();

		SubThread sub = new SubThread(lock, 50);
		sub.start();

		MainThread thread = new MainThread(lock, 50);
		thread.start();

	}

	public void run() {
		while (true) {
			if (this.num < limit) {
				this.num++;
			} else {
				synchronized (lock) {
					lock.notify(); // 通知子线程结束
					System.out.println("通知子线程结束");
				}
				break;
			}
			synchronized (lock) {
				lock.notify();
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			for (int i = 0; i < 100; i++) {
				System.out.println("MainThread:" + i);
			}
		}
		System.out.println("Main end.");
	}

}


public class SubThread extends Thread {
	private Object lock;
	private int limit;
	private int num;

	public SubThread(Object lock, int limit) {
		this.lock = lock;
		this.limit = limit;
	}

	@Override
	public void run() {
		while (true) {
			if (this.num < limit) {
				this.num++;
			} else {
				break;
			}
			for (int i = 0; i < 10; i++) {
				System.out.println("SubThread:" + i);
			}
			synchronized (lock) {
				lock.notify();
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("Sub end.");
	}
}

你可能感兴趣的:(java)