昨天晚上的一道笔试题目,感觉很吃力,没有IDE工具编写,单词都不知道怎么写了,哎,还是练得不够,今天就简单整理一下该笔试题目。
感觉还是有点问题,后期再更新一下。
class ThreadAndNumber {
public static void main(String[] args) {
Object o = new Thread();
ThreadA threadA = new ThreadA(o);
ThreadB threadB = new ThreadB(o);
threadA.start();
threadB.start();
}
}
class ThreadA extends Thread {
private Object object;
public ThreadA(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {
for (int i = 1; i <= 26; i++) {
System.out.println(i);
if (i % 2 == 0) {
object.notifyAll(); //唤醒其他线程
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class ThreadB extends Thread{
private Object object;
public ThreadB(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {
for (int i = 1; i <= 26; i++) {
System.out.println((char) ('A' + i));
if (i % 2 == 0) {
object.notifyAll(); //唤醒其他线程
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}