/**
* Created by chengtao on 17/12/3.
* 多个线程 如何共享数据?
* 常见实例:多个窗口同时售卖火车票
*/
public class Thread0701_MultiThreadShareData {
public static void main(String[] args) {
SaleTicket data1 = new SaleTicket();
new Thread(data1).start();
new Thread(data1).start();
}
static class SaleTicket implements Runnable{
private int count = 100;
public void run() {
while (true){
synchronized (this){
if(count>0){
count--;
System.out.println( Thread.currentThread().getName() + " 剩余票数 " + count);
}
}
}
}
}
}
/*
以上代码 适用于 执行方法相同的场景,因为执行的代码相同,
所以多个线程可以 传入同一个runnable接口的实现类,在实现类中定义和处理数据
进而实现数据的共享
如果 线程执行的代码不同:如有的线程对变量加一 有的线程对变量减一
*/
-----------------------------
-----------------------------
-----------------------------
/**
* Created by chengtao on 17/12/3.
*/
public class Thread0702_MultiThreadShareData {
private static ShareData1 data1 = new ShareData1();
public static void main(String[] args) {
ShareData1 data2 = new ShareData1();
new Thread(new MyRunnable1(data2)).start();
new Thread(new MyRunnable2(data2)).start();
final ShareData1 data1 = new ShareData1();
new Thread(new Runnable(){
public void run() {
data1.decrement();
}
}).start();
new Thread(new Runnable(){
public void run() {
data1.increment();
}
}).start();
}
}
class MyRunnable1 implements Runnable{
private ShareData1 data1;
public MyRunnable1(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.decrement();
}
}
class MyRunnable2 implements Runnable{
private ShareData1 data1;
public MyRunnable2(ShareData1 data1){
this.data1 = data1;
}
public void run() {
data1.increment();
}
}
class ShareData1 {
private int j = 0;
public synchronized void increment(){
j++;
}
public synchronized void decrement(){
j--;
}
}