引言
首先問這樣一個問題
volatile
競爭和同步?
鎖機制?
線程安全問題?
線程池和隊列?
好吧
可是
不如換一個思路
另外
誕生
Java的基因來自於
JDK
搶占式和協作式是兩種常見的進程/線程調度方式
一種線程間的通信方式是使用中斷
public class InterruptCheck extends Thread {
@Override
public void run() {
System
while (true)
if (Thread
break;
System
}
public static void main(String[] args) {
Thread thread = new InterruptCheck();
thread
try {
sleep(
} catch (InterruptedException e) {
}
thread
}
}
這是中斷的一種使用方式
public class InterruptWait extends Thread {
public static Object lock = new Object();
@Override
public void run() {
System
synchronized (lock) {
try {
lock
} catch (InterruptedException e) {
System
Thread
System
e
}
}
}
public static void main(String[] args) {
Thread thread = new InterruptWait();
thread
try {
sleep(
} catch (InterruptedException e) {
}
thread
}
}
在這種方式下
在比較穩定的JDK
值得一提的是
import ncurrent
public class Atomicity {
private static volatile int nonAtomicCounter =
private static volatile AtomicInteger atomicCounter = new AtomicInteger(
private static int times =
public static void caculate() {
times++;
for (int i =
new Thread(new Runnable() {
@Override
public void run() {
nonAtomicCounter++;
atomicCounter
}
})
}
try {
Thread
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
caculate();
while (nonAtomicCounter ==
nonAtomicCounter =
atomicCounter
caculate();
}
System
+ nonAtomicCounter);
System
}
}
上面這個例子你也許需要跑幾次才能看到效果
對於鎖的使用
public class Lock {
private static Object o = new Object();
static Lock lock = new Lock();
// lock on dynamic method
public synchronized void dynamicMethod() {
System
sleepSilently(
}
// lock on static method
public static synchronized void staticMethod() {
System
sleepSilently(
}
// lock on this
public void thisBlock() {
synchronized (this) {
System
sleepSilently(
}
}
// lock on an object
public void objectBlock() {
synchronized (o) {
System
sleepSilently(
}
}
// lock on the class
public static void classBlock() {
synchronized (Lock
System
sleepSilently(
}
}
private static void sleepSilently(long millis) {
try {
Thread
} catch (InterruptedException e) {
e
}
}
public static void main(String[] args) {
// object lock test
new Thread() {
@Override
public void run() {
lock
}
}
new Thread() {
@Override
public void run() {
lock
}
}
new Thread() {
@Override
public void run() {
lock
}
}
sleepSilently(
System
// class lock test
new Thread() {
@Override
public void run() {
lock
}
}
new Thread() {
@Override
public void run() {
lock
}
}
}
}
上面的例子可以反映對一個鎖競爭的現象
非靜態方法使用synchronized修飾
靜態方法使用synchronized修飾
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27270.html