class="java" name="code">package com.lj.thread2;
public class Sample
{
private int number;
// 实现number加1
public synchronized void increase()
{
while (0 != number)
{
try
{
wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number++;
System.out.println("number increased by "+Thread.currentThread().getName()+", number= "+ number);;
notify();
}
public synchronized void decrease(){
while(0==number){
try
{
wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number--;
System.out.println("number decreased by "+Thread.currentThread().getName()+", number= "+ number);;
notify();
}
}
这里定义了对象类, 实现数字在1和0之间进行不停的转换。
package com.lj.thread2;
public class IncreaseThread extends Thread
{
private Sample sample;
public IncreaseThread(Sample sample){
this.sample=sample;
}
@Override
public void run()
{
for(int i=0;i<20;i++){
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
sample.increase();
}
}
}
对数字加1的
线程.
package com.lj.thread2;
public class DecreaseThread extends Thread
{
private Sample sample;
public DecreaseThread(Sample sample){
this.sample=sample;
}
@Override
public void run()
{
for(int i=0;i<20;i++){
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
sample.decrease();
}
}
}
减1的线程
package com.lj.thread2;
public class Test
{
public static void main(String[] args)
{
Sample s=new Sample();
Thread increase=new IncreaseThread(s);
Thread decrease=new DecreaseThread(s);
Thread i2=new IncreaseThread(s);
Thread d2=new DecreaseThread(s);
increase.start();
i2.start();
decrease.start();
d2.start();
}
}
这里的重点就是while
循环那里不能写if。因为一个线程如果处于wait阶段,当它wait结束的时候, 要运行的时候必须再验证一下condition是否符合。
使用if的话不会去进行验证, 会直接执行number++或者number--, 导致
错误。