zoukankan      html  css  js  c++  java
  • 一个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;
    	  }
    }
    

      

  • 相关阅读:
    jboss hello world
    jboss 7 启动问题
    jboss [how to access the admin console]
    tomee 消息持久化
    Python、C和Java对比
    编程语言产生时间表
    从关系型数据库到非关系型数据库
    约束和异常处理
    类与类之间的关系
    类的成员
  • 原文地址:https://www.cnblogs.com/xujishou/p/6639099.html
Copyright © 2011-2022 走看看