在 Java 传统线程机制中的共享数据方式,大致可以简单分两种情况:
1、多个线程行为一致,共同操作一个数据源。也就是每个线程执行的代码相同,可以使用同一个 Runnable 对象,这个 Runnable 对象中有那个共享数据。
public class SellTicket {
public static void main(String[] args) {
Ticket t = new Ticket();
new Thread(t).start();
new Thread(t).start();
}
}
class Ticket implements Runnable {
private int ticket = 10;
public void run() {
synchronized (this) {
while(ticket > 0){
ticket--;
System.out.println("当前票数为:"+ticket);
}
}
}
}
2、多个线程行为不一致,共同操作一个数据源。也就是每个线程执行的代码不同,这时候需要用不同的Runnable 对象。
public class Acount {
private int money;
public Acount(int money){
this.money=money;
}
public synchronized void getMoney(int money){
//注意这个地方必须用while循环,因为即便再存入钱也有可能比取的要少
while(this.money < money) {
System.out.println("取款:" + money + " 余额:" + this.money + " 余额不足,正在等待存款......");
try {
wait();
} catch(Exception e){
}
}
this.money = this.money - money;
System.out.println("取出:" + money + " 还剩余:" + this.money);
}
public synchronized void setMoney(int money) {
try{
Thread.sleep(10);
} catch(Exception e){
}
this.money = this.money + money;
System.out.println("新存入:" + money + " 共计:" + this.money);
notify();
}
public static void main(String args[]){
Acount Acount = new Acount(0);
Bank b = new Bank(Acount);
Consumer c = new Consumer(Acount);
new Thread(b).start();
new Thread(c).start();
}
}
//存款类
class Bank implements Runnable {
Acount Acount;
public Bank(Acount Acount) {
this.Acount = Acount;
}
public void run() {
while(true) {
int temp = (int)(Math.random() * 1000);
Acount.setMoney(temp);
}
}
}
//取款类
class Consumer implements Runnable {
Acount Acount;
public Consumer(Acount Acount) {
this.Acount=Acount;
}
public void run() {
while(true) {
int temp=(int)(Math.random() * 1000);
Acount.getMoney(temp);
}
}
}