多線程的同步依靠的是對象鎖機制
下面以一個簡單的實例來進行對比分析
先來看第一段代碼
代碼
package com
class MyThread implements java
private int threadId;
public MyThread(int id) {
this
}
@Override
public synchronized void run() {
for (int i =
System
}
}
}
public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for (int i =
new Thread(new MyThread(i))
Thread
}
}
}
從上述代碼段可以得知
基於這種思想
代碼
package com
class MyThread implements java
private int threadId;
private Object lock;
public MyThread(int id
this
this
}
@Override
public void run() {
synchronized (lock) {
for (int i =
System
}
}
}
}
public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
for (int i =
new Thread(new MyThread(i
Thread
}
}
}
從第二段代碼可知
代碼
package com
class MyThread implements java
private int threadId;
private static Object lock = new Object();
public MyThread(int id) {
this
}
@Override
public void run() {
synchronized (lock) {
for (int i =
System
}
}
}
}
public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for (int i =
new Thread(new MyThread(i))
Thread
}
}
}
再來看第一段代碼
代碼
package com
class MyThread implements java
private int threadId;
public MyThread(int id) {
this
}
@Override
public void run() {
taskHandler(this
}
private static synchronized void taskHandler(int threadId) {
for (int i =
System
}
}
}
public class ThreadDemo {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for (int i =
new Thread(new MyThread(i))
Thread
}
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27441.html