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