今天去面试,碰到几道题目,分享下,看看做对了没有。。。。
1、创建四个线程,他们会分别对 j 减一,然后 j 为 0 ,j的初始值为10.
我是这样写的
package test;
public class Test {
private int j = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t = new Test();
t.test();
}
void test() {
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
t1.start();
t2.start();
t3.start();
t4.start();
}
class MyThread extends Thread implements Runnable {
@Override
public synchronized void run() {
// TODO Auto-generated method stub
while (j > 0) {
--j;
if (j < 0) {
return;
} else {
System.out.println(this.getName() + " : " + j);
}
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
2、老问题,2、比较两个字符串,输出正否,例如“aab”与“aba”这两字串输出true
我回来以后,做出来是这样子的……
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "aba";
String b = "baa";
Test2 t = new Test2();
long startTime = System.nanoTime();
System.out.println(t.compare(new StringBuffer(a), b));
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
}
private Boolean compare(StringBuffer a, String b) {
for (int i = 0; i < b.length(); i++) {
String str = ""+b.charAt(i);
a.deleteCharAt(a.indexOf(str));
}
return a.length() == 0 ? true : false;
}
}
3、这个是什么来着,取出一堆字符串里面的数字,还把,这道题我也垮了,原来是很简单的,结果我写了好复杂
public class Test3 {
public static void main(String[] args) {
String a = "sfet654tgdfgr5tgrfgr5tgrt5";
a = a.replaceAll("\\D","");
System.out.println(a);
}
}