为什么我得到不规则的输出? [英] Why I am getting an irregular output?

查看:78
本文介绍了为什么我得到不规则的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

包核心; 

公共类MT3 {
public static void main(String args []){
Account acc1 = new Account();
//帐户acc2 =新帐户();
AThread ath1 =新AThread(acc1,A);
BThread ath2 =新的BThread(acc1,B);
}
}
类帐户{
public synchronized void withdraw(){
for(int i = 0; i< 5; i ++){
System.out.println(Withdraw \t:+ Thread.currentThread()。getName());
try {
Thread.sleep(500);
} catch(例外e){
e.printStackTrace();
}
}
} void deposite(){
for(int i = 0; i< 5; i ++){
System.out.println(Deposite \t:+ Thread.currentThread()的getName());
try {
Thread.sleep(500);
} catch(例外e){
e.printStackTrace();
}
}
}
}
类AThread实现Runnable {
Account acc;
public AThread(Account acc,String tname){
this.acc = acc;
线程t1 =新线程(this,tname);
t1.start();
}
public void run(){
acc.withdraw();
}
}
类BThread实现Runnable {
Account acc;
public BThread(Account acc,String tname){
this.acc = acc;
线程t2 =新线程(this,tname);
t2.start();
}
public void run(){
acc.deposite();
}
}





我的尝试:



我使用的是单个对象,撤销方法是同步的,我无法弄清楚不规则输出的原因。

解决方案

< blockquote>你正在试验我们称之为'竞争条件'

竞争条件 - 维基百科 [ ^ ]


package core;

public class MT3 {
public static void main(String args[]) {
	Account acc1 = new Account();
//	Account acc2 = new Account();
	AThread ath1 = new AThread(acc1, "A");
	BThread ath2 = new BThread(acc1, "B");
}
}
class Account{
	public  synchronized void withdraw() {
		for (int i = 0; i<5; i++) {
			System.out.println("Withdraw \t:"+Thread.currentThread().getName());
			try {
				Thread.sleep(500);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}  void deposite(){
		for (int i=0;i<5;i++) {
			System.out.println("Deposite \t:"+Thread.currentThread().getName());
			try {
				Thread.sleep(500);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}
class AThread implements Runnable{
	Account acc;
	public AThread(Account acc, String tname) {
		this.acc=acc;
		Thread t1 = new Thread(this,tname);
		t1.start();
	}
	public void run() {
		acc.withdraw();
	}
}
class BThread implements Runnable{
	Account acc;
	public BThread(Account acc, String tname) {
		this.acc=acc;
		Thread t2 = new Thread(this,tname);
		t2.start();
	}
	public void run() {
		acc.deposite();
	}
}



What I have tried:

I am using single object and the withdraw method is sync, I can't figure out the reasin for irregular output.

解决方案

You are experimenting what we call a 'race condition'
Race condition - Wikipedia[^]


这篇关于为什么我得到不规则的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆