1、银行有一个账户有两个储户存分别向同一个账户存3000 元,每次存1000, 存3次 。每次存完打印账户余额
问题:该程序是否有安全问题,如果有,如何解决?
【提示】
1,明确哪些代码是多线程运行代码,须写入run()方法
2,明确什么是共享数据。
3,明确多线程运行代码中哪些语句是操作共享数据的
package com.cgtn.test;
class putMoney implements Runnable {
private static int money;
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (money < 3000) {
money += 1000;
System.out.println(Thread.currentThread().getName() + ":" + money);
}
}
}
}
public class test1 {
public static void main(String[] args) {
putMoney p1 = new putMoney();
Thread t1 =new Thread(p1);
Thread t2 =new Thread(p1);
t1.setName("一号");
t2.setName("二号");
t1.start();
t2.start();
}
}
2、线程通信的例子:使用两个线程打印 1-100。线程1, 线程2 交替打印
package com.cgtn.test;
class putMoney implements Runnable {
private int num=1;
@Override
public void run() {
while (true) {
synchronized (this) {
if (num <= 100) {
this.notify();
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
} else {
break;
}
try {
this.wait();
} catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class test1 {
public static void main(String[] args) {
putMoney p1 = new putMoney();
Thread t1 =new Thread(p1);
Thread t2 =new Thread(p1);
t1.setName("一号");
t2.setName("二号");
t1.start();
t2.start();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)