前天去一家做数据挖掘的公司面试,有一题是关于java多线程的,现贴出来和网友分享。
题目:启动两个线程,第一个线程输出1,第二个线程输出a,接着第一个线程输出11,第二个线程输出aa,以此类推。
既输出为 1 a 11 aa 111 aaa 1111 aaaa .....。
代码是我自己写的,如有不妥的地方,欢迎指正。
package thread.writtentest;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
final Share share = new Share();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
share.print1();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
share.printA();
}
}
}).start();
}
}
class Share {
//输出1或a的个数
static int length = 1;
String a = "a";
int i = 1;
//isExc=true时,第一个线程执行RUNNABLE状态,第二个线处于WAITING状态。
//isExc=false时,第二个线程执行RUNNABLE状态, 第一个线程处于WAITING状态。
boolean isExc = true;
public synchronized void print1() {
while (!isExc) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
}
for (int index = 0; index < length; index++) {
System.out.print(i);
}
System.out.println();
isExc = false;
notifyAll();
}
public synchronized void printA() {
while (isExc) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
}
for (int index = 0; index < length; index++) {
System.out.print(a);
}
length++;
System.out.println();
isExc = true;
notifyAll();
}
}