(1)线程1开始执行加1,然后wait一毫秒
(2)这一毫秒里面线程2执行一次,然后wait住
(3)线程1等待一毫秒后自动获取资源的锁,然后唤醒线程2进入就绪状态
(4)线程1还没有释放锁,所以继续循环一次,然后wait一毫秒
(5)这时候线程2可以运行一次并wait
然后重复(3-5)最后直到退出循环。
package com.thread;
public class TwoThread
{
public static void main(String[] args)
{
Counter c = new Counter();
new Thread(new ThreadOne(c),"线程1").start();
new Thread(new ThreadTwo(c),"线程2").start();
}
}
class ThreadOne implements Runnable
{
Counter c;
public ThreadOne(Counter c)
{
this.c = c;
}
/**
*
*/
public void run()
{
synchronized (c)
{
while (c.value < 10)
{
c.value++;
System.out.println(Thread.currentThread().getName() + "将value加1,value = "
+ c.value);
try
{
c.wait(1);//释放对c的同步锁一毫秒,这样线程2就有机会可以执行了(线程2执行后就wait住了)
c.notify();//在一毫秒过后线程1自动获取锁后开始执行,唤醒线程2 ,但不是立即线程2就可以执行,而是等线程一在下一次wait(1):释放同步锁后才开始
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class ThreadTwo implements Runnable
{
Counter c;
public ThreadTwo(Counter c)
{
this.c = c;
}
/**
*
*/
public void run()
{
synchronized (c)
{
while (c.value < 10)
{
c.value++;
System.out.println(Thread.currentThread().getName() + "将value加1,value = "
+ c.value);
try
{
c.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class Counter
{
int value;
/**
* @return value
*/
public int getValue()
{
return this.value;
}
}