/*
1,4个窗口分别卖100张票
class Ticket extends Thread
{
public void run()
{
for (int x = 1;x <= 100 ;x++ )
{
System.out.println(this.getName()+x);
}
}
}
class day11
{
public static void main(String[] args)
{
new Thread(new Ticket()).start();
new Thread(new Ticket()).start();
}
}
2,4个窗口共卖100张票
注意安全问题,使用两种方式解决
class Ticket implements Runnable
{
private int ticket = 100;
public void run()
{
while (true)
{
synchronized (this)
{
if(ticket > 0)
{
System.out.println(Thread.currentThread().getName()+ (ticket--));
}
}
}
}
}
class day11
{
public static void main(String[] args)
{
Ticket ticket = new Ticket();
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
}
}
3,两个帐户向金库存钱,分别存入300,存3次
class Bank implements Runnable
{
private int sum = 0;
public void run()
{
for (int x = 0;x < 3;x++)
{
synchronized (this)
{
System.out.println(Thread.currentThread().getName()+(sum +=100));
}
}
}
}
class day11
{
public static void main(String[] args)
{
Bank bank = new Bank();
new Thread(bank).start();
new Thread(bank).start();
}
}
4,单例设计模式,注意安全问题
//饿汉式
class Single
{
private final Single single = new Single();
public Single getInstance()
{
return single;;
}
}
//懒汉式
class Single
{
private Single single = null;
public Single getInstance()
{
if (single == null)
{
synchronized (this)
{
if (single == null)
{
this.single = new Single;
return single;
}
}
}
else
return single;
}
}
5,写一个死锁程序
*/
class DeadLock implements Runnable
{
private boolean flag;
DeadLock(boolean flag)
{
this.flag = flag;
}
public void run()
{
if (flag)
{
while (true)
{
synchronized (l.a)
{
System.out.println("if lock a");
synchronized(l.b)
{
System.out.println("if lock b");
}
}
}
}
else
{
while (true)
{
synchronized (l.b)
{
System.out.println("else lock b");
synchronized (l.a)
{
System.out.println("else lock a");
}
}
}
}
}
}
class l
{
static Object a = new Object();
static Object b = new Object();
}
class day11
{
public static void main(String[] args)
{
Object a = new Object();
Object b = new Object();
new Thread(new DeadLock(true)).start();
new Thread(new DeadLock(false)).start();
}
}