同步两种方式:synchronized关键字 Lock 锁住
package Test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 一个线程打印5次,另一个打印3次,交替循环3次
*
* synchronized+ this.wait()+this.notify()
* 等于Lock.lock()+unlock()+lock.newCondition()+ await()+signal()
* 不同的是lock需要手动释放unlock互斥锁,而synchronized不需要
*
* mutex锁只能用于race condition不破坏critical section,
* 要具体指定哪个线程访问必须有个flag,也就是这里的isOne
* */
public class Ex1 {
public static void main(String[] args){
//final Run r = new Run();
final Run2 r = new Run2();
new Thread(new Runnable(){
@Override
public void run() {
for(int i=0;i<3;i++)
r.thread1();
}
}).start();
new Thread(new Runnable(){
public void run(){
for(int i=0;i<3;i++)
r.thread2();
}
}).start();
}
}
class Run{
private boolean isOne = true;
synchronized void thread1(){
while(!isOne){ //一定是循环等待,防止误唤醒
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+":第"+i+"次");
}
isOne = false;
this.notify();
}
synchronized void thread2(){
while(isOne){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int i=1;i<=3;i++){
System.out.println(Thread.currentThread().getName()+":第"+i+"次");
}
isOne = true;
this.notify();
}
}
class Run2{
boolean isOne = true;
Lock lock = new ReentrantLock();
Condition c = lock.newCondition();
void thread1(){
lock.lock();
try{
while(!isOne){
try{
c.await();
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int i=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":第"+i+"次");
isOne = false;
c.signal();
}finally{
lock.unlock();
}
}
void thread2(){
lock.lock();
try{
while(isOne){
try{
c.await();
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int i=1;i<=3;i++)
System.out.println(Thread.currentThread().getName()+":第"+i+"次");
isOne = true;
c.signal();
}finally{
lock.unlock();
}
}
}