synchronized
,当一个线程获得对象的排他锁,独占资源,其他资源必须等待,使用后释放锁即可,存在下列问题:
package syn;
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"学生").start();
new Thread(station,"旅客").start();
new Thread(station,"黄牛").start();
}
}
class BuyTicket implements Runnable{
private int tickeynums = 10;
boolean flag = true; //外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if(tickeynums <= 0){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+tickeynums--);
}
}
package syn;
//模拟银行取钱
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100,"结婚基金"); //100为当前卡里的总金额
Drawing you = new Drawing(account,50,"张伟"); //我取走50
Drawing girlfriend = new Drawing(account,100,"女朋友"); //女朋友取走100
you.start();
girlfriend.start();
}
}
//账户
class Account{
int money; //余额
String name; //卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account; //银行拥有账户
//取了多少钱
int drawingMoney;
//当前拥有的钱数
int nowMoney;
//构造方法
public Drawing(Account account, int drawingMoney, String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//重写run方法:取钱
@Override
public void run() {
//首先判断还有没有钱
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//取钱操作:卡内余额 = 余额 - 取出的钱
account.money = account.money - drawingMoney;
//手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//this.getName() = Thread.currentThread().getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
synchronized
方法控制对"对象"的访问,每个对象对应一把锁,每个synchronized
方法都必须获得调用该方法的对象的锁才能执行,否则线程被阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
给之前买票的例子上同步方法,只需在方法上加关键字即可。
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(tickeynums <= 0){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+tickeynums--);
}
格式:synchronized(obj){}
,obj称为同步监视器,同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是对象本身。
改写上面银行取钱的例子:
将对账户类的操作放入同步块中(锁的对象就是变化的量,需要增删改的对象)
@Override
public void run() {
//首先判断还有没有钱
synchronized (account){
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//取钱操作:卡内余额 = 余额 - 取出的钱
account.money = account.money - drawingMoney;
//手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//this.getName() = Thread.currentThread().getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
java.util.concunrrent.lock.Lock
接口控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能由一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象synchronized
相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock
,可以显式加锁、释放锁。例:未加锁的情况
package syn;
public class LockTest {
public static void main(String[] args) {
LockTest2 testLock2 = new LockTest2();
//三个线程同时操作一个资源
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class LockTest2 implements Runnable{
int numTickets = 10;
@Override
public void run() {
while (true){
if (numTickets > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(numTickets--);
}
else {
break;
}
}
}
}
package syn;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public static void main(String[] args) {
LockTest2 testLock2 = new LockTest2();
//三个线程同时操作一个资源
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class LockTest2 implements Runnable{
int numTickets = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
//票要变化,所以在票这里加锁
try{
lock.lock(); //加锁
if (numTickets > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(numTickets--);
}
else {
break;
}
}
finally {
//解锁
lock.unlock();
}
}
}
}