1.在很多情况下,主线程创建子线程,如果希望主线程等待子线程完成之后再结束,就要用到join()方法了,方法join()的作用是等待线程对象销毁。join()是一个同步方法,需要获得对应线程的锁才能执行,因为它本质是一个wait(),所以join()会释放对应的锁,join(Long)表示最多等待多少毫秒,但是想要继续执行,还是要抢到对应线程的锁。join()源码:
public final void join() throws InterruptedException {
join(0);//调用下面的方法
}
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
2.Lock锁 ReentrantLock() https://www.cnblogs.com/Wanted-Tao/p/6378942.html
ReentrantReadWriteLock()锁https://www.cnblogs.com/Wanted-Tao/p/6379363.html
3.lock,condition实现轮流输出A,B,C
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private volatile static int key=1;
private static Lock lock=new ReentrantLock();
private static Condition conditionA=lock.newCondition();
private static Condition conditionB=lock.newCondition();
private static Condition conditionC=lock.newCondition();
static class ThreadA extends Thread{
@Override
public void run() {
while (true) {
try {
lock.lock();
while (key != 1) {
conditionA.await();
}
System.err.println("A");
key = 2;
conditionB.signal();
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}
}
static class ThreadB extends Thread{
@Override
public void run() {
while (true) {
try {
lock.lock();
while (key != 2) {
conditionB.await();
}
System.err.println("B");
key = 3;
conditionC.signal();
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}
}
static class ThreadC extends Thread{
@Override
public void run() {
while (true) {
try {
lock.lock();
while (key != 3) {
conditionC.await();
}
System.err.println("C");
key = 1;
conditionA.signal();
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
Thread threadA=new ThreadA();
Thread threadB=new ThreadB();
Thread threadC=new ThreadC();
threadA.start();
threadB.start();
threadC.start();
}
}