java——多线程——内部类共享同一个外部类对象的成员变量

时间:2021-06-03 22:54:19
public class Shop
{
public static void main(String[] args)
{
Outer o=new Outer();
Thread t1=o.getSale("T1 ");
Thread t2=o.getSale("T2 ");
/*Thread t1=new Thread(o,"T1");
Thread t2=new Thread(o,"T2");*/
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName()); } }
class Outer
{
Object temp=new Object();
private int ticket=100;
public Thread getSale(String s)
{
return new Sale(s);
} class Sale extends Thread//implements Runnable//
{ Sale(String s)
{
super(s); }
public void run()
{ while(ticket>0)
{
try
{
Thread.currentThread().sleep(10);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
saletTicket(getName());
} }
private void saletTicket(String s)
{
synchronized (temp)
{
if(ticket>0)
{
System.out.println(getName()+" ticket "+ticket--);
//ticket=tmp;
} } } }
} /*public class Shop {
public static void main(String[] args) {
Outer o = new Outer();
o.getSale("s1:").start();
o.getSale("s2:").start();
}
} class Outer {
private int ticket = 100; public Thread getSale(String s) { return new Sale(s);
} private class Sale extends Thread {
Sale(String s) {
super(s);
} public void run() {
while(ticket > 0){ try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket(getName());
}
}
} public synchronized void ticket(String name){
if (ticket > 0) {
System.out.println(name + " ticket " + ticket--);
}
}
}*/

错误代码如下,这样只会让先抢到资源的线程执行到底。循环应放置在同步区外部

public class Shop
{
public static void main(String[] args)
{
Outer o=new Outer();
Thread t1=o.getSale("T1 ");
Thread t2=o.getSale("T2 ");
Thread t1=new Thread(o,"T1");
Thread t2=new Thread(o,"T2");
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName()); } }
class Outer
{
Object temp=new Object();
private int ticket=100;
public Thread getSale(String s)
{
return new Sale(s);
} class Sale extends Thread//implements Runnable//
{ Sale(String s)
{
super(s); }
public void run()
{ try
{
Thread.currentThread().sleep(10);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} saletTicket(getName()); }
private void saletTicket(String s)
{
synchronized (temp)
{
while(ticket>0)
{
System.out.println(getName()+" ticket "+ticket--);
//ticket=tmp;
} } } }
}