TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
我今天来解释下wai与与notify的用法了。
其实也是非常简单的,就是个消费与生产的问题,当消费大于生产值的时候就使消费线程停止,等待生产线程的通知
class Test
{
int value = 30;
public synchronized int getValue()
{
return value;
}
public Test()
{
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}
public synchronized void increase() //Test的生产方法
{
value++;
if(value > 30)
notify();
}
public synchronized void decrease() //Test的消费方法
{
try
{
value -= 8;
if(value <= 0)
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
class T
extends Thread
{
public void run()
{
while(true)
{
dos();
}
}
public T(String n)
{
this.setName(n);
}
public synchronized void dos()
{
try
{
System.out.println(Thread.currentThread().getName() + " " + value);
if("t1".equals(Thread.currentThread().getName()))
{
increase(); //叫做t1的线程负责Test的生产
}
if("t2".equals(Thread.currentThread().getName()))
{
decrease(); //叫做t2的线程负责Test的消费
}
Thread.currentThread().sleep(200);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String argv[])
{
Test t1 = new Test();
}
}
这里注意的是Test的类使用wai方法来阻止消费线程继续消费。 程序运行结果:
C:java>java Test
t1 30
t2 31
t1 23
t2 24
t1 16
t2 17
t1 9
t2 10
t1 2
t2 3
t1 -5
t1 -4
t1 -3
t1 -2
t1 -1
t1 0
t1 1
t1 2
t1 3
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t1 10
t1 11
t1 12
t1 13
t1 14
t1 15
t1 16
t1 17
t1 18
t1 19
t1 20
t1 21
t1 22
t1 23
t1 24
t1 25
t1 26
t1 27
t1 28
t1 29
t1 30
t1 31
t2 32
t1 24
t2 25
t1 17
t2 18
t1 10
t2 11
t1 3
t2 4
t1 -4
t1 -3
t1 -2
t1 -1
t1 0
t1 1
t1 2
t1 3
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t1 10
t1 11 。。。。。。 C:java>
源码下载:http://file.javaxxz.com/2014/10/28/235649718.zip |
|