本帖最后由 、__WSD吴少东 于 2013-4-15 13:35 编辑
- class Ticket implements Runnable
- {
- private int tick = 10000;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if(flag)//使用if else 进行转换。
- {
- while(true)
- {
- synchronized(obj)
- {
- show();//要执行的代码
- }
- }
- }
- else
- while(true)
- show();//要执行的代码
- }
- public synchronized void show()//同步函数,用的是this锁
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"........."+tick--);
- }
- }
- }
- }
- class SiSuo
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();//创建资源
- Thread t1 = new Thread(t);//创建t资源的线程
- Thread t2 = new Thread(t);
- t1.start();//启动线程
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag = false;
- t2.start();
- }
- }
复制代码- class Tick implements Runnable
- {
- boolean fals;
- Tick(boolean fals)
- {
- this.fals = fals;
- }
- public void run()
- {
- if(fals)
- {
- while(true)
- {
- synchronized(MyLock.locka)
- {
- System.out.println("if locka");
- synchronized(MyLock.lockb)
- {
- System.out.println("if lockb");
- }
- }
- }
- }
- else
- {
- synchronized(MyLock.lockb)
- {
- System.out.println("else lockb");
- synchronized(MyLock.locka)
- {
- System.out.println("else locka");
- }
- }
- }
- }
- }
- class MyLock
- {
- static Object locka = new Object();
- static Object lockb = new Object();
- }
- class SiSuo1
- {
- public static void main(String[] args)
- {
- Thread t1 = new Thread(new Tick(true)); //这里想不明白,这是不是创建了两个不同的对象? 和第一种死锁有什么不同的地方。除了锁
- Thread t2 = new Thread(new Tick(false));
- t1.start();
- t2.start();
- }
- }
复制代码 |