所属的字节码文件
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s==null){
synchronized(Single.class){
if(s==null)
s = new Single();
}
}
return s;
}
}
class SingleDemo{
public static void main(String[] args){
}
}
死锁:
你持有一个锁,我持有一个锁,我到你那里运行,要拿你的锁,你要到我里面运行,要拿
我的锁,你也不给锁,我也不让锁,程序就挂了,产生死锁。
同步中嵌套同步,而锁却不同
线程间通信:
其实就是多个线程在操作同一个资源,但是操作的动作不同。
等待唤醒机制:
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
if(flag){
try(r.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag){
try(r.wait();}catch(Exception e){}
System.out.println(name+"....."+sex);
flag = false;
this.notify();
}
}
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0){
r.set( "mike","man");
}else{
r.set( "丽丽","女女");
}
x = (x+1)%2;
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
class InputOutputDemo{
public static void main(String[] args){
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}