一:线程之间的通讯
/*
线程之间的通讯:对共同资源访问
但是操作不同
注意:多个线程同时做一个动作,需要while(falg)判断
notifyAll唤醒。
*/
class res
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
private res r;
Input(res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exception e){}
if(x == 0)
{
r.name = "make";
r.sex = "man";
}
else
{
r.name = "小丽";
r.sex = "女";
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
class Output implements Runnable
{
private res r;
Output(res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"........."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
class Thread2
{
public static void main(String[] args)
{
res r = new res();
Input i = new Input(r);
Output o = new Output(r);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
二:同步函数
/*
同步函数的锁是this
静态同步方不是this,是类名.class
静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
死锁:
同步中嵌套同步!
*/
class Test
{
private boolean flag;
Tead(boolean flag)
{
this.flag = flag;
}
public void run()
{
if(flag)
{
synchronized(a)
{
System.out.println("if a");
synchronized(b)
{
System.out.println("if b");
}
}
}
else
{
synchronized(b)
{
System.out.println("else b");
synchronized(a)
{
System.out.println("else a" );
}
}
}
}
}
class lack
{
Object a = new Object();
Object b = new Object();
}
class MyLock
{
}
class DeadLockTest
{
}
class Thread3
{
public static void main(String[] args)
{
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}