一个java多线程面试题

线程a 打印 数字 0--12;

线程b 打印 字母 a--z;

打印结果:0ab1cd2ef3gh4ij5kl6mn7op8qr9st10uv11wx12yz

要求用到 线程间传值;

分析:线程a打印一个数字,线程b打印两个字母 , 进行13次循环,

通过公共资源类进行线程间传值

public class FftThreadTest {
public static void main(String[] args) {
		//创建final资源对象
		final Business business = new Business();
		char c='a';
                 
		for(int i=0;i<=12;i++){
			business.pringtInt(i);
			business.setC(c);
			new Thread(
					new Runnable() {
						@Override
						public void run() {
							business.pringtString();
						}
					}
			).start();
			c=(char)((int)c+2);
		}
		
	}
	
}

/**
业务类:1打印数字,2打印字母,  
**/
class Business {
	private boolean isInt=true; //标记是否打印数字
	private char c; //要打印的字母
         //打印数字  同步锁
	public synchronized void pringtInt(int i){
                //如果不是数字等待
		while(!isInt){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(i);
                //修改标记
		isInt=false;
		this.notify(); //唤醒等待线程
	}
	
        //打印字母 同步锁
	public synchronized void pringtString(){
                //如果是数字等待
		while(isInt){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
                //打印两个字母
		for(int i=0;i<2;i++){
			System.out.print(c);
			c++;
		}
                //修改标记
		isInt=true;
		this.notify(); //唤醒等待线程
	}
	public void setC(char c){
		  this.c=c;
	  }
}

  

posted @ 2017-03-29 12:00  徐继收  阅读(474)  评论(0编辑  收藏  举报