package thread;
/**
*
* synchronized關鍵字實現多線程同步
*(1)靜態變量爲全部對象共享,能夠對其加鎖,實如今同步
*(2)靜態方法加鎖,鎖住的是類,也可實現同步
*/
public
class PrintNum
implements Runnable
{
private
int id;
private
static Object lock =
new Object();
public PrintNum(
int id)
{
this.id = id;
}
// 方法1:對靜態變量加鎖
// public void run()
// {
//
// synchronized (lock)
// {
// for (int i = 0; i < 100; i++)
// {
//
// System.out.println("Thread-" + id + ":" + i);
// }
// }
//
// }
//方法2:對靜態方法加鎖
public
void run()
{
taskHandler(id);
}
synchronized
public
static
void taskHandler(
int id)
{
for (
int i = 0; i < 100; i++)
{
System.out.println(
"Thread-" + id +
":" + i);
}
}
public
static
void main(String args[])
{
for (
int i = 0; i < 10; i++)
{
new Thread(
new PrintNum(i)).start();
//the flowing code just for test
for(
int j = 1;j<10;j++)
{
if(j==9)
{
System.out.println(
"wait me for a while..."); } } } } }