5.lock 锁
中断: 线程实例.interrupt();
lock锁的使用
package com.jlong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class User {
public String name;
public String sex;
public boolean flag = false;
public Lock lock = new ReentrantLock();
public Condition conditionLock = lock.newCondition();
}
class InputThread extends Thread {
private User user;
public InputThread(User user) {
this.user = user;
}
int cout = 0;
@Override
public void run() {
while (true) {
//加锁
user.lock.lock();
if (user.flag) {
try {
//线程等待
user.conditionLock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
if (cout == 0) {
user.name = "jLong";
user.sex = "男";
} else {
user.name = "燕子";
user.sex = "女";
}
cout = (cout + 1) % 2;
user.flag = true;
//唤醒一个在 await()等待队列中的线程。与Object.notify()相似
user.conditionLock.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
//解锁
user.lock.unlock();
}
}
}
}
class OutputThread extends Thread {
private User user;
public OutputThread(User user) {
this.user = user;
}
@Override
public void run() {
while (true) {
user.lock.lock();
if (!user.flag) {
try {
user.conditionLock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println(user.name + "--" + user.sex);
user.flag = false;
user.conditionLock.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
user.lock.unlock();
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
User user = new User();
InputThread inputThread = new InputThread(user);
OutputThread outputThread = new OutputThread(user);
inputThread.start();
outputThread.start();
}
}