package com.ghgj.cn.thread;
public class ThreadABC {
static Object abc = new Object();
static Boolean thread1=true;
static Boolean thread2=false;
static Boolean thread3=false;
static int i=0;
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){//循环10次
synchronized (abc){//当前线程获取静态对象()
while(thread1==false){//条件分支,这里不能用if
try {
System.out.println("aa");
abc.wait();//主动释放对象锁,同时本线程休眠
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("a");
thread1=false;//保证本线程不死
thread2=true;//唤醒2线程
thread3=false;//保证3线程不死
abc.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
synchronized (abc){
while(thread2==false){
try {
abc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("b");
thread1=false;
thread3=true;
thread2=false;
abc.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
synchronized (abc){
while(thread3==false){
try {
abc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("c");
thread1=true;
thread2=false;
thread3=false;
abc.notifyAll();
}
}
}
}).start();
}
}
在同一时间只有一个线程可访问该类的实例.
线程间相互唤醒的话就需要借助Object.wait(), Object.nofity()了。
Thread.sleep()与Object.wait()二者都可以暂停当前线程,释放CPU控制权,主要的区别在于Object.wait()在释放CPU同时,释放了对象锁的控制,而sleep不会,理解了这些解决这道面试题应该就不成问题了
参考自:https://blog.csdn.net/shinehuaking2011/article/details/8112432