我正在尝试做一个银行帐户应用程序,这将与线程运行。我想有3个不同的银行帐户,但我不确定怎么做。
我的代码如下:
package bankapp1;
public class Account implements Runnable {
int balance;
int preTransaction;
String customerName;
String customerId;
Account()
{
balance = 6000;
}
public void run() {
for (int i =1; i <=4; i++) {
deposit(2000);
if (getBalance() < 0 ) {
System.out.println("account is overdrawn!");
}
}
}
public synchronized void deposit (int amount) {
if (getBalance() >= amount ) {
System.out.println(Thread.currentThread().getName() + " is going to withdraw $ "
+ amount);
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
}
withdraw(amount);
System.out.println(Thread.currentThread().getName() + " completes the withdrawl of $ "
+ amount);
} else {
System.out.println(" not enought in account for " + Thread.currentThread().getName()
+ "to withdraw" + getBalance());
}
}
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
if (amount!=0) {
balance = balance - amount;
preTransaction = -amount;
}
}
void getPreTransaction()
{
if (preTransaction > 0)
{
System.out.println("Deposited: " +preTransaction);
}
else if (preTransaction < 0) {
System.out.println("Withdrawn: " + Math.abs(preTransaction));
}
else {
System.out.println("No transaction occured");
}
}
}
package bankapp1;
public class ClientTesting {
public static void main(String[] args) {
Account acc = new Account();
Thread t1 = new Thread(acc);
Thread t2 = new Thread(acc);
t1.setName("pinelopi");
t2.setName("andreas");
t1.start();
t2.start();
}
}
我是否必须创建另一个名为savingsAccount的类,其实现与Account类几乎相同,然后在ClientTesting类中调用它,就像我对Account类所做的那样?
发布于 2018-10-24 05:05:09
试试像这样的东西。
public class Account1 implements Runnable {
@Override
public void run() {
try {
//logic here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Account2 implements Runnable
public class Account3 implements Runnable
public interface ThreadFactory {
Thread newTread(Runnable runnable);
}
public class MyThreadFactory implements ThreadFactory {
private String name;
public MyThreadFactory(String name){
this.name = name;
}
@Override
public Thread newTread(Runnable runnable) {
Thread t = new Thread(runnable);
}
// here addition logic (deposit, getBalance, ...)
public class Main {
public static void main(String[] args) {
MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
Thread th1 = factory.newTread(new Account1());
Thread th2 = factory.newTread(new Account2());
Thread th3 = factory.newTread(new Account3());
th1.start();
th2.start();
th3.start();
发布于 2018-10-24 10:13:46
您可以将Runnable
任务提交给ExecutorService
,如下所示:
ExecutorService execService = null;
try {
Account acc = new Account();
execService = Executors.newFixedThreadPool(2);
execService.submit(acc);
execService.submit(acc);
execService.submit(acc);
} finally {
execService.shutdown();
}
https://stackoverflow.com/questions/52957047
复制相似问题