看视频毕老师讲的 线程同步中,毕老师的代码如下:
class Bank
{
private int sum=0;
public void add(int a)
{
sum = sum + a;
System.out.println("总金额为:"+sum);
}
}
class User implements Runnable
{
Bank b = new Bank();
public void run()
{
for (int i = 0;i<3 ;i++ )
{
b.add(100);
}
}
}
public class Demo
{
public static void main(String [] args)
{
User u = new User();
Thread t1 = new Thread(u);
Thread t2 = new Thread(u);
t1.start();
t2.start();
}
}
这样会出现安全性问题。
但是为什么 在存钱时,来一个用户 创建一个用户 也就是下面代码
public class Demo
{
public static void main(String [] args)
{
User u1 = new User();
User u2 = new User();
Thread t1 = new Thread(u1);
Thread t2 = new Thread(u2);
t1.start();
t2.start();
}
}
|
|