1. LockSupport
public class XC01 {
static Thread t1=null,t2 = null;
public static void main(String[] args) {
char[] c1 = "ABCDEF".toCharArray();
char[] c2 = "123456".toCharArray();
t1 = new Thread(()->{
for (char c : c1) {
System.out.println(c);
LockSupport.unpark(t2);
LockSupport.park();
}
});
t2 = new Thread(()->{
for (char c : c2) {
LockSupport.park();
System.out.println(c);
LockSupport.unpark(t1);
}
});
t1.start();
t2.start();
}
}
2. 自旋锁 cas
public class XC02 {
enum RunThead{T1,T2}
static RunThead runThead = RunThead.T1;
public static void main(String[] args) {
char[] c1 = "ABCDEF".toCharArray();
char[] c2 = "123456".toCharArray();
new Thread(()->{
for (char c : c1) {
while (runThead!=RunThead.T1){}
System.out.println(c);
runThead = RunThead.T2;
}
}).start();
new Thread(()->{
for (char c : c2) {
while (runThead!=RunThead.T2){}
System.out.println(c);
runThead = RunThead.T1;
}
}).start();
}
}
3. wait和notify
控制顺序也可以用自旋锁 和CountDownLatch
public class XC03 {
public static void main(String[] args) {
char[] c1 = "ABCDEF".toCharArray();
char[] c2 = "123456".toCharArray();
Object o = new Object();
new Thread(() -> {
synchronized (o) {
try {
//控制顺序 打开就先输出1
// o.notify();
// o.wait();
for (char c : c1) {
System.out.println(c);
o.notify();
o.wait();
}
o.notify(); //防止程序一直等待
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
synchronized (o) {
try {
for (char c : c2) {
System.out.println(c);
o.notify();
o.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
o.notify();
}
}).start();
}
}
4. lock 一个Condition
public class XC04 {
public static void main(String[] args) {
char[] c1 = "ABCDEF".toCharArray();
char[] c2 = "123456".toCharArray();
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
condition.await();
for (char c : c1) {
System.out.println(c);
condition.signal();
condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
lock.lock();
for (char c : c2) {
System.out.println(c);
condition.signal();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
5.两个Condition
condition可以理解成是队列
public class XC05 {
public static void main(String[] args) {
char[] c1 = "ABCDEF".toCharArray();
char[] c2 = "123456".toCharArray();
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
condition1.await();
for (char c : c1) {
System.out.println(c);
condition2.signal();
condition1.await();
}
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
lock.lock();
for (char c : c2) {
System.out.println(c);
condition1.signal();
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
condition1.signal();
}).start();
}
}