java中有个两种锁,第一种是synchronize锁(之前已经讲过),现在来研究一下LOCK锁。
下面看个测试:
测试类:
public class Test {
static Print print = new Print();
static Thread1 thread1 = new Thread1();
static Thread2 thread2 = new Thread2();
public static void main(String[] args) {
new Thread(thread1).start();
new Thread(thread2).start();
}
public static class Thread1 implements Runnable{
@Override
public void run() {
System.out.println("this is first thread start");
print.print();
System.out.println("this is first thread end");
}
}
public static class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("this is sencond thread start");
print.print();
System.out.println("this is sencond thread end");
}
}
}
打印类;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Print {
Lock lock = new ReentrantLock();
public void print(){
lock.lock();
System.out.println("print....");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
}
}
输出:
this is first thread start
this is sencond thread start
print....(运行到print()方法的时候锁住代码块,如果没有锁住另一个线程也会输出print...这个需要读者根据代码逻辑自己想清楚)
this is first thread end
print....
this is sencond thread end
下面把lock去掉,如下:
打印类:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Print {
Lock lock = new ReentrantLock();
public void print(){
System.out.println("print....");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试类和上面相同就不贴了
输出