package test;
public class MyThread extends Thread
{
/**
*
* @param name thread's name
*/
public MyThread(String name)
{
super(name);
}
// goods cnt
static int cnt = 20;
// lock
static Object ob = "ZENGWENFENG";
public void run()
{
while (cnt > 0)
{
synchronized (ob)
{
if (cnt > 0)
{
System.out.println(getName() + " --- NO." + cnt + " --- ");
cnt--;
}
else
{
System.out.println("Game Over!");
}
}
try
{
sleep(1000);//sleep 1000ms
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
package test;
public class ZzzTest
{
/**
* java synchronized lock
*
* @author ZengWenFeng
*/
public static void main(String[] args)
{
//
MyThread station1 = new MyThread("thread_zwf_01");
MyThread station2 = new MyThread("thread_zwf_02");
MyThread station3 = new MyThread("thread_zwf_03");
//
station1.start();
station2.start();
station3.start();
}
}
thread_zwf_01 --- NO.20 ---
thread_zwf_03 --- NO.19 ---
thread_zwf_02 --- NO.18 ---
thread_zwf_02 --- NO.17 ---
thread_zwf_01 --- NO.16 ---
thread_zwf_03 --- NO.15 ---
thread_zwf_01 --- NO.14 ---
thread_zwf_03 --- NO.13 ---
thread_zwf_02 --- NO.12 ---
thread_zwf_03 --- NO.11 ---
thread_zwf_02 --- NO.10 ---
thread_zwf_01 --- NO.9 ---
thread_zwf_02 --- NO.8 ---
thread_zwf_01 --- NO.7 ---
thread_zwf_03 --- NO.6 ---
thread_zwf_02 --- NO.5 ---
thread_zwf_01 --- NO.4 ---
thread_zwf_03 --- NO.3 ---
thread_zwf_02 --- NO.2 ---
thread_zwf_03 --- NO.1 ---
Game Over!