解决了多线程的安全问题
多个线程判断锁,较为耗费资源
class ThreadDemo1 {
public static void main(String[] args) {
Ticket tic = new Ticket();
Thread t1 = new Thread(tic);
Thread t2 = new Thread(tic);
Thread t3 = new Thread(tic);
t1.start();
t2.start();
t3.start();
}
}
class Ticket implements Runnable {
private int ticket = 500;
Object obj = new Object();
public void run() {
while (true) {
synchronized (obj) {
if (this.ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ... " + this.ticket);
this.ticket--;
}
}
}
}
}
class ThreadDemo2 {
public static void main(String[] args) {
Customer cus = new Customer();
Thread t1 = new Thread(cus);
Thread t2 = new Thread(cus);
t1.start();
t2.start();
}
}
/**
* 一个银行,有两个客户向银行存钱,每个客户有300元,每次均是存100元,每个人存3次
* */
class Bank{
private int sumMoney;
public synchronized void add(int money){
this.sumMoney = this.sumMoney + money;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sumMoney = " + this.sumMoney);
}
}
class Customer implements Runnable{
private Bank bank = new Bank();
public void run(){
for (int i = 1; i<=3; i++){
bank.add(100);
}
}
}
原文地址:http://blog.csdn.net/u011402596/article/details/44929409