多线程学习(四):Lock锁与线程优先级
1. Lock锁的基本用法
- 创建Lock实例
- Lock lock = new ReentrantLock();
- 使用lock()方法获取锁
- 使用unLock()方法释放锁
- 通常,一般unLock()方法会被放在finally块中,以保证在异常情况下lock锁被正常释放,
private final Lock lock = new ReentrantLock();
lock.lock();
try{
// 同步代码
} finally {
lock.unlock();
}
public class ThreadLock1 implements Runnable{
private int count = 100;
private final Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count > 1) {
lock.lock();
try{
count--;
System.out.println(Thread.currentThread().getName() + ":" + count);
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
ThreadLock1 threadLock = new ThreadLock1();
new Thread(threadLock).start();
new Thread(threadLock).start();
}
}
2. Condition的基本用法
- 获取Condition实例
- Condition condition = lock.newCondition();
- await()阻塞线程
- signal()唤醒线程
- 与wait()/notify()需要在同步代码块中使用类似,await()/signal()在使用前需要获取lock锁,使用后需要释放锁
public class ThreadLock2 implements Runnable{
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<即将进入等待状态>");
lock.lock();
try {
condition.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName() + "<执行结束>");
}
void signal() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "<线程即将被唤醒>");
condition.signal();
System.out.println(Thread.currentThread().getName() + "<线程已被唤醒>");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ThreadLock2 threadLock = new ThreadLock2();
new Thread(threadLock).start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
threadLock.signal();
}
}
3. 线程优先级
- 设置优先级:thread.setPriority(int newPriority);
- 优先级范围:1 —— 10
- 默认优先级:5
- 线程优先级只是一个调度提示,高优先级的线程不一定会比低优先级的线程先执行。
public class ThreadPriority implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public static void main(String[] args) {
ThreadPriority threadPriority = new ThreadPriority();
Thread thread1 = new Thread(threadPriority, "t1");
Thread thread2 = new Thread(threadPriority, "t2");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}
本文是原创文章,转载请注明来自 Lazyking.site
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果
Steam卡片