如何在两个线程之间共享数据
总
1,如果每个线程执行的代码相同,可以使用同一个Runnable对象,这个Runnable对象中有那个共享数据,例如,卖票系统就可以这么做。
2,如果每个线程执行的代码不同,这时候需要用不同的Runnable对象,例如,设计4个线程。其中两个线程每次对j增加1,另外两个线程对j每次减1,银行存取款
每个线程执行的代码相同,可以使用同一个Runnable对象
public class RunnalbleTest2 implements Runnable { private int threadCnt = 10; @Override public void run() { while (true) { if (threadCnt > 0) { System.out.println(Thread.currentThread().getName() + " 剩余个数 " + threadCnt); threadCnt--; try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } public static void main(String[] args) { RunnalbleTest2 runnalbleTest2 = new RunnalbleTest2(); new Thread(runnalbleTest2).start(); new Thread(runnalbleTest2).start(); } }
结果
Thread-0 剩余个数 10 Thread-1 剩余个数 10 Thread-0 剩余个数 8 Thread-1 剩余个数 7 Thread-0 剩余个数 6 Thread-1 剩余个数 5 Thread-0 剩余个数 4 Thread-1 剩余个数 3 Thread-0 剩余个数 2 Thread-1 剩余个数 1
每个线程执行的代码不同,用不同的Runnable对象
#
public class Acount { private int money; Acount(int money) { this.money = money; } public synchronized void getMoney(int money) { while (this.money < money) { System.out.println("余额不足"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } this.money -= money; System.out.println("取出" + money + ",还剩" + this.money); } public synchronized void setMoney(int money) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } this.money += money; System.out.println("新存入" + money + ",总额:" + this.money); notify(); } public static void main(String[] args) { Acount acount = new Acount(0); Bank bank = new Bank(acount); Consumer consumer = new Consumer(acount); new Thread(bank).start(); new Thread(consumer).start(); } }
#
import java.util.Random; public class Bank implements Runnable{ Acount acount; public Bank(Acount acount) { this.acount = acount; } @Override public void run() { while(true) { int random = (int)(Math.random() * 1000); acount.setMoney(random); } } }
#
public class Consumer implements Runnable{ Acount acount; Consumer(Acount acount) { this.acount = acount; } @Override public void run() { while (true) { int random = (int)(Math.random() * 1000); acount.getMoney(random); } } }
结果
新存入442,总额:442 余额不足 新存入196,总额:638 新存入815,总额:1453 取出534,还剩919 新存入402,总额:1321 取出719,还剩602 取出11,还剩591 ....