package zhu.test;
/**
* 需求:
* 使同一份数据分别进行 加1 减1 交替出现 10次
* @author nn
*
*/
public class ThreadShareDataDemo1 {
public static void main(String[] args) {
final ShareDATA DataObj= new ShareDATA();//静态方法内不允许非静态内部类
//线程 1 增加
new Thread(
new Runnable() {
@Override
public void run()
{
for(int i=0;i<10;i++)
DataObj.add();
}
}
).start();
//线程2 减少
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++)
DataObj.incre();
}
}
).start();
}
}
class ShareDATA{
boolean isAddTrue=true;
int data;
synchronized void incre()
{
if(isAddTrue)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data--;
System.out.println("inre"+this.data);
this.isAddTrue=true;
this.notify();
}
synchronized void add()
{
if(!this.isAddTrue)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data++;
System.out.println("add"+this.data);
this.isAddTrue=false;
this.notify();
}
}
/**
* 需求:
* 使同一份数据分别进行 加1 减1 交替出现 10次
* @author nn
*
*/
public class ThreadShareDataDemo1 {
public static void main(String[] args) {
final ShareDATA DataObj= new ShareDATA();//静态方法内不允许非静态内部类
//线程 1 增加
new Thread(
new Runnable() {
@Override
public void run()
{
for(int i=0;i<10;i++)
DataObj.add();
}
}
).start();
//线程2 减少
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++)
DataObj.incre();
}
}
).start();
}
}
class ShareDATA{
boolean isAddTrue=true;
int data;
synchronized void incre()
{
if(isAddTrue)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data--;
System.out.println("inre"+this.data);
this.isAddTrue=true;
this.notify();
}
synchronized void add()
{
if(!this.isAddTrue)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data++;
System.out.println("add"+this.data);
this.isAddTrue=false;
this.notify();
}
}