線程同步,什麼是同步? 同步就是防止對共享資源訪問導致數據不一致的一種模式。打個比方:兩個人在打電話,一個人說完了,另一個人接着說,也就是你一下,我一下,這就是同步。若是兩個人打電話兩個人都同時在說,不管對方說的是什麼內容,你幹你的,我幹我的,這就是異步。
線程同步程序實例1:子線程循環10次,接着主線程循環100次,接着又回到子線程循環10次,接着在回到這線程有循環100,如此循環50次,請寫出程序。
package cn.itcast.thread;
/**
* 子線程循環10次,接着主線程循環100次,
* 接着又回到子線程循環10次,接着在回到這線程有循環100,
* 如此循環50次,請寫出程序。
* @author asus
*/
public class TraditionalThreadWait {
public static void main(String[] args) {
new TraditionalThreadWait().init();
}
private void init() {
final Business business = new Business();
new Thread(){
public void run() {
for (int i=1; i<=50; i++) {
//synchronized (this) {
business.sub(i);
//}
}
}
}.start();
for (int i=1; i<=50; i++) {
//synchronized (this) {
business.main(i);
//}
}
}
}
class Business {
boolean isShouldSub = true;
public synchronized void sub(int seq) {
if (!isShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i=0; i<10; i++) {
System.out.println("sub thread loop ---->" + seq);
}
isShouldSub = false;
this.notify();
}
public synchronized void main(int seq) {
if (isShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i=0; i<=100; i++) {
System.out.println("main thread loop ----->" + seq);
}
isShouldSub = true;
this.notify();
}
}
線程同步程序實例2: 寫四個線程,兩個線程對j加1, 另外兩個對j減1
package cn.itcast.thread;
public class ThreadDataShare3 {
/**
* 寫四個線程,兩個線程對j加1, 另外兩個對j減1
* @param args
*/
public static void main(String[] args) {
/*final JManager jManager = new JManager();
for (int i=0; i<2; i++) {
new Thread(new Runnable() {
public void run() {
jManager.increment();
}
}).start();
new Thread(new Runnable() {
public void run() {
jManager.increment();
}
}).start();
}
*/
new ThreadDataShare3().init();
}
private int j = 0;
public void init() {
for (int i=0; i<10; i++) {
new Thread(new Runnable() {
public void run() {
synchronized (ThreadDataShare3.this) {
j ++;
System.out.println(j);
}
}
}).start();
new Thread(new Runnable() {
public void run() {
synchronized (ThreadDataShare3.this) {
j --;
System.out.println(j);
}
}
}).start();
}
}
}
class JManager {
private int j = 0;
public synchronized void increment() {
j ++;
}
public synchronized void decrement() {
j --;
}
}
總結:如果每個線程執行的代碼相同,可以使用同一個Runnable對象,這個Runnable對象中有那個共享數據(聲明一個類,擁有共享數據,讓他實現Runnable接口);如果每個線程執行的代碼不同, 這時候就需要用不同的Runnable對象