20211115Java面试题

1、下面一段代码能输出1,2,3,4...10吗?若不能,请指出有问题的地方,并改正。

public class ThreadDemo{

private static volatile int count=0;

public static void main(String[] args) throws InterruptedException {

for(int i=0;i<5;i++)

{

    Thread a=new Thread(){

        public void run()

        {

            for(int i=0;i<2;i++)

            {

                try {

                    TimeUnit.MILLISECONDS.sleep(50);

                    count++;

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println(count+(count!=10?",":""));

            }

        }

    };

    a.start();

}

}

}

不能。

违反了多线程的原子性操作。

Object lock=new Object();
for(int i=0;i<5;i++)
{
    Thread a=new Thread(){
        public void run()
        {
            synchronized (lock) {
                for (int i = 0; i < 2; i++) {
                        count++;
                System.out.println(count+(count!=10?",":""));
            }
                lock.notifyAll();
            }

        }
    };
    a.start();
}

2、使用99个线程,顺序打印1到99

private static volatile int count = 0;

public void ThreadSynchronizedTest()

{

    Object lock = new Object();

    for(int i=1;i<=99;i++)

    {

        //每个线程一个编号

        int num=i;

        Thread thread=new Thread(new Runnable() {

            @Override

            public void run() {

                try{

                    synchronized (lock)

                    {

                        while (count!=num)

                        {

                            lock.wait();

                        }

                        System.out.println(Thread.currentThread().getName()+":"+num);

                        count++;

                        lock.notifyAll();

                    }

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        },"thread-"+num);

        thread.start();

    }

    synchronized (lock)

    {

       count++;

       lock.notifyAll();

    }

}

3、找出字符串中小写字母个数

a-z:97-122,A-Z:65-90,0-9:48-57

方法一:int count=0;
String aa="dfdSedfdsdfdTESc";
char[] arr=aa.toCharArray();
for(int j=0;j<arr.length;j++)
{
    if(arr[j]>97)//char类型可以自动转换为int类型
    {
        System.out.println(arr[j]);
        count++;
    }
}
System.out.println(count);

方法二

int count=0;
String aa="dfdSedfdsdfdTESc";
for(int i=0;i<aa.length();i++)
if(aa.charAt(i)>='a'&&aa.charAt(i)<='z')
{
    count++;
}
System.out.println(count);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值