import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private Lock lock = new ReentrantLock();
public void func1(){
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.println(i+" ");
}
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
Main main = new Main();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(main::func1);
executorService.execute(main::func1);
}
}
输出:
0 1 2 3 4 5 6 7 8 9 -
0 1 2 3 4 5 6 7 8 9 -
其实这段代码等价于
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public synchronized void func1(){
for (int i = 0; i < 10; i++) {
System.out.print(i+" ");
}
System.out.println("-");
}
public static void main(String[] args) {
Main main = new Main();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(main::func1);
executorService.execute(main::func1);
}
}
此时可以发现ReentrantLock
中和java关键字synchronized
起到的效果是一样的.只不过synchronized
是JVM提供的,ReentrantLock
是jdk中的类.
性能上在jdk1.8上可以优先选用JVM关键字synchronized
notify
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NotifyExample {
public synchronized void before(){
System.out.println("before");
notify();
}
public synchronized void after(){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
NotifyExample notifyExample = new NotifyExample();
executorService.execute(notifyExample::after);
executorService.execute(notifyExample::before);
}
}
输出
before
after
fun after中的wait()
就是进入等待状态并释放线程锁.然后before线程执行,6行中输出然后notify,之前的进入wait()
状态的线程继续执行.
© 著作权归作者所有
文章评论(0)