面试过程中遇到的代码问题 --- 两个线程交替输出

package shr.facetest;

/**
 * @Author: 史皓燃
 * @CreateDate 2019/1/11 15:44
 * <h1>两个线程交替打印  1A2B3C4D.....9I1J.....Z</h1>
 */
public class ThreadPrint {

	static final Object object = new Object();

	public static void main(String[] args) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=1;i<= 26;i++){
					synchronized (object){
						object.notify();
						try {
							object.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.print(i);
						object.notify();
					}
				}

			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				for(char i= 'A';i<= 'Z' ;i++){
					synchronized (object){
						object.notify();
						try {
							object.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.print(i);

					}
				}
			}
		}).start();

	}
}

猜你喜欢

转载自blog.csdn.net/qq_42046342/article/details/86304415