java多线程面试题

前天去一家做数据挖掘的公司面试,有一题是关于java多线程的,现贴出来和网友分享。
题目:启动两个线程,第一个线程输出1,第二个线程输出a,接着第一个线程输出11,第二个线程输出aa,以此类推。
既输出为 1 a 11 aa 111 aaa 1111 aaaa .....。

代码是我自己写的,如有不妥的地方,欢迎指正。

package thread.writtentest;

public class ThreadTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Share share = new Share();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					share.print1();
				}
			}

		}).start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					share.printA();
				}
			}

		}).start();
	}

}

class Share {

	//输出1或a的个数
	static int length = 1;
	String a = "a";
	int i = 1;
	
	//isExc=true时,第一个线程执行RUNNABLE状态,第二个线处于WAITING状态。
	//isExc=false时,第二个线程执行RUNNABLE状态, 第一个线程处于WAITING状态。
	boolean isExc = true;

	public synchronized void print1() {
		while (!isExc) {
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}

		for (int index = 0; index < length; index++) {
			System.out.print(i);
		}
		
		System.out.println();
		isExc = false;
		notifyAll();

	}

	public synchronized void printA() {
		while (isExc) {
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}

		for (int index = 0; index < length; index++) {
			System.out.print(a);
		}

		length++;
		System.out.println();
		isExc = true;
		notifyAll();
	}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值