多線程之線程同步(一)

<code>synchronized修飾一個靜態的方法.
靜態方法是屬於類的而不屬於對象的。同樣的,synchronized修飾的靜態方法鎖定的是這個類的所有對象/<code>


<code>public synchronized static void method() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); }
}
}

// 如果使用run()來啟動線程,就不是異步執行了,而是同步執行,不會達到使用線程的意義。
public synchronized void run() {
method();
}/<code>
<code>private static int count;
public Thr() {
count = 0;
}

public static void main(String [] args){
// Thr implements Runnable;Thread類本身也是實現了Runnable接口
Thr th = new Thr();
Thr th2 = new Thr();
Thread thread = new Thread(th,"t1");
Thread thread2 = new Thread(th2,"t2");
// 啟動線程 ,出現異步執行的效果
thread.start();
thread2.start();}/<code>

run:

多線程之線程同步(一)


補充:1.Thread類本身也是實現了Runnable接口.

2.如果使用run()來啟動線程,就不是異步執行了,而是同步執行,不會達到使用線程的意義。

3.調用線程的start方法是創建了新的線程,在新的線程中執行。
調用線程的run方法是在主線程中執行該方法,和調用普通方法一樣,


分享到:


相關文章: