class Bank
{
private int sum;
Object obj = new Object();
public synchronized void add(int n)
{
sum = sum + n;
System.out.println("sum="+sum);
}
}
class Cus implements Runnable
{
private Bank b = new Bank();
public void run()
{
for(int x=0;x<3;x++)
{
b.add(100);
}
}
}
class BankDemo
{
public static void main(String[] args)
{
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
运行结果为:
sum=100
sum=200
sum=300
sum=400
sum=500
sum=600
我想问的是把Cus c这个对象传进Thread构造函数里,执行时不是只有一个Cus c 对象吗?for(int x=0;x<3;x++)
应该只能执行3次,不论多少个线程,输出结果应该是
sum=100
sum=200
sum=300
前面有个TicketDemo2,里面有100张票,不论多少线程访问都不会超过100,顺便贴下代码
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
System.out.println(Thread.currentThread().getName()+"sale:"+ tick--);
}
}
}
}
}
class TicketDemo2
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}