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;
    	  }
    }
    

      

  • 相关阅读:
    转:npm安装教程
    转:数据库收缩
    转:日志插件 log4net 的使用
    转:更改SQLServer实例默认字符集
    转:IIS 应用程序池 内存 自动回收
    IDisposable
    Sql Server 判断字符串是否可以转数字
    常用算法之快速排序
    Java调用JavaScript
    使用python生成iOS各规格icon
  • 原文地址:https://www.cnblogs.com/xujishou/p/6639099.html
Copyright © 2011-2022 走看看