线程出现重复取和重复赋值的情况
class Info{
private String name;
private String content;
public void setName(String name){
this.name = name ;
}
public void setContent(String content){
this.content = content ;
}
public String getName(){
return this.name ;
}
public String getContent(){
return this.content ;
}
public synchronized void set(String name, String content){
this.setName(name);
try{
Thread.sleep(300);
}catch(Exception e){
e.printStackTrace();
}
this.setContent(content);
}
public synchronized void get(){
try{
Thread.sleep(300);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(this.getName() + "<--->" + this.getContent());
}
}
class Producer implements Runnable{
private Info info;
public Producer(Info info){
this.info = info;
}
@Override
public void run(){
boolean flag = false;
for (int i=0;i<50 ;i++ ){
if(flag){
this.info.set("123", "789");
flag = false;
}else{
this.info.set("abc", "xyz");
flag = true;
}
}
}
}
class Consumer implements Runnable{
private Info info;
public Consumer(Info info){
this.info = info;
}
@Override
public void run(){
for(int i=0;i<50 ;i++ ){
this.info.get();
}
}
}
public class T3 {
public static void main(String[] args) {
Info info = new Info();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}
利用Object类的wait()和notify()方法
class Info{
private String name = "123";
private String content = "789";
private boolean flag = false;
public void setName(String name){
this.name = name ;
}
public void setContent(String content){
this.content = content ;
}
public String getName(){
return this.name ;
}
public String getContent(){
return this.content ;
}
public synchronized void set(String name, String content){
if(!flag){
try{
super.wait();
}catch(Exception e){
e.printStackTrace();
}
}
this.setName(name);
try{
Thread.sleep(300);
}catch(Exception e){
e.printStackTrace();
}
this.setContent(content);
flag = !flag;
super.notify();
}
public synchronized void get(){
if(flag){
try{
super.wait();
}catch(Exception e){
e.printStackTrace();
}
}
try{
Thread.sleep(300);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(this.getName() + "<--->" + this.getContent());
flag = !flag;
super.notify();
}
}
class Producer implements Runnable{
private Info info;
public Producer(Info info){
this.info = info;
}
@Override
public void run(){
boolean flag = false;
for (int i=0;i<50 ;i++ ){
if(flag){
this.info.set("123", "789");
flag = false;
}else{
this.info.set("abc", "xyz");
flag = true;
}
}
}
}
class Consumer implements Runnable{
private Info info;
public Consumer(Info info){
this.info = info;
}
@Override
public void run(){
for(int i=0;i<50 ;i++ ){
this.info.get();
}
}
}
public class T4 {
public static void main(String[] args) {
Info info = new Info();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}