スレッド切り替え
1322 ワード
import org.junit.jupiter.api.Test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* ThreadCount too young too simple
*
* @Date 2019/1/24
* @Author joker
**/
public class ThreadCount {
private static volatile int i = 1;
public static void main(String[] args) {
test();
}
public static void test() {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Runnable runnable = () -> {
lock.lock();
try {
for (; i <= 100; ) {
try {
System.out.println(i++);
condition.signal();
//
if (i == 101) {
return;
}
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
}
}