JAVA多线程(二)

[size=x-large]资源竞争 (线程互斥)[/size]
[size=medium]1、什么是资源竞争[/size]
  有这样一种资源,在某一时刻只能被一个线程所使用:比如打印机、某个文件等等,如果多个线程不加控制的同时使用这类资源,必然会导至错误。
  下面的例子模拟了一个打印机,多个线程不加控制的同时使用这个打印机:
public class Printer
{
public void print(int printer, String content)
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}

public static void main(String[] args)
{
Printer p = new Printer();

for (int i=0; i<3; i++)
new Thread(new MyThread(p)).start();
}
}

class MyThread implements Runnable
{
private static int counter = 0;
private final int id = counter++;

private Printer printer;

public MyThread(Printer printer)
{
this.printer = printer;
}

@Override
public void run()
{
printer.print(id, "Content of " + id);
}

}

  输出结果(sample)
Start working for [0]
Start working for [1]
===================
===================
Start working for [2]
Content of 0
Content of 1
===================
===================
===================
Content of 2
Work complete for [0]

Work complete for [1]

===================
Work complete for [2]

  从结果可以看到,打印机的输出完全乱套了,各个线程想要打印的内容全部参杂在一起了。

[size=medium]2、解决资源竞争问题[/size]
  原则上要解决这类问题并不难,只需要一个锁的机制。任何线程在使用打印机前必须先对打印机上锁;在使用完打印机后释放锁;如果线程尝试对打印机上锁时别的线程已经上了锁,则该线程必须等待别的线程先释放锁。
  Java中,解决上述资源共享类的问题是通过关键字synchronized实现的。java中的对象都有一个‘锁’,这样,任何一个线程尝试访问对象的synchronized方法时,必须要先获得对象的'锁',否则必须等待。
  一个对象可能会有多个synchronized方法,比如synchronized a()方法和synchronized b()方法。当一个线程获得了对象的锁,进行a()方法、或b()方法了,那么在线程释放该对象的锁之前,别的线程是不能访问该对象的其它synchronized方法的。
  下面例子是之前的例子的改良版本,只需要简单的把Printer对象的print方法定义成synchronized的就可以达到我们的要求了:
public class Printer
{
public synchronized void print(int printer, String content)
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}

public static void main(String[] args)
{
Printer p = new Printer();

for (int i=0; i<3; i++)
new Thread(new MyThread(p)).start();
}
}

class MyThread implements Runnable
{
private static int counter = 0;
private final int id = counter++;

private Printer printer;

public MyThread(Printer printer)
{
this.printer = printer;
}

@Override
public void run()
{
printer.print(id, "Content of " + id);
}

}

  输出结果
Start working for [0]
===================
Content of 0
===================
Work complete for [0]

Start working for [2]
===================
Content of 2
===================
Work complete for [2]

Start working for [1]
===================
Content of 1
===================
Work complete for [1]

  从结果的输出可以看出来,被模拟的打印机资源在某一时刻,仅被一个线程所使用。

[size=medium]3、临界区[/size]
  有些时候,你可能不需要隔离整个方法,而只需要隔离方法中的部分代码,这部分被隔离的代码就叫做临界区。临界区中的代码在某一时刻,只能被一个线程访问。
  下面的例子,是用临界区的方式实现了前面的例子:
public class Printer
{
public void print(int printer, String content)
{
synchronized(this)
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}
}

public static void main(String[] args)
{
Printer p = new Printer();

for (int i=0; i<3; i++)
new Thread(new MyThread(p)).start();
}
}

class MyThread implements Runnable
{
private static int counter = 0;
private final int id = counter++;

private Printer printer;

public MyThread(Printer printer)
{
this.printer = printer;
}

@Override
public void run()
{
printer.print(id, "Content of " + id);
}

}

  可以看到,在Java中临界区也是通过synchronized关键字实现的。在synchronized关键字后面,要传一个对象参数,任何线程要进入临界区时必须先要获得该对象的锁,退出临界区时要释放该对象的锁,这样别的线程才有机会进入临界区。
  从上面两个例子可以看出,临界区和synchronized方法,其原理都是一样的,都是通过在对象上加锁来实现的,只不过临界区来得更加灵活,因为它不光可以对this对象加锁,也可以对任何别的对象加锁。

[size=medium]4、Lock[/size]
  Java1.5提供了一个显示加锁的机制,比起synchronized方式来说,显示加锁的方法可能让代码看上去更加复杂,但是也带来了更好的灵活性。
  下面的例子,用Lock的机制实现了前面的例子:
public class Printer
{
private Lock lock = new ReentrantLock();

public void print(int printer, String content)
{
lock.lock();

try
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}
finally
{
lock.unlock();
}
}

public static void main(String[] args)
{
Printer p = new Printer();

for (int i=0; i<3; i++)
new Thread(new MyThread(p)).start();
}
}

class MyThread implements Runnable
{
private static int counter = 0;
private final int id = counter++;

private Printer printer;

public MyThread(Printer printer)
{
this.printer = printer;
}

@Override
public void run()
{
printer.print(id, "Content of " + id);
}

}

  使用Lock的时候,必须要注意两点:
[list]
[*]锁的释放必须放在finally块里面,以保证锁被正确的释放;
[*]如果被隔间的方法或临界间需要返回一个值,那么return语句应该放在try块中,从而不至于使unlock发生得过早而导至错误的发生。
[/list]
  使用显示的Lock机制,可以让程序更加的灵活。比如上面的例子中,如果尝试使用打印机的时候,打印机正被别的线程所使用,那么早取消本次打印。要实现这样的功能,使用synchronized可能不太容易实现,但是使用Lock机制的话,就非常简单了:
public class Printer
{
private Lock lock = new ReentrantLock();

public void print(int printer, String content)
{
boolean isLocked = lock.tryLock();

if (!isLocked)
return;

try
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}
finally
{
if(isLocked)
lock.unlock();
}
}

public static void main(String[] args)
{
Printer p = new Printer();

for (int i=0; i<3; i++)
new Thread(new MyThread(p)).start();
}
}

class MyThread implements Runnable
{
private static int counter = 0;
private final int id = counter++;

private Printer printer;

public MyThread(Printer printer)
{
this.printer = printer;
}

@Override
public void run()
{
printer.print(id, "Content of " + id);
}

}

  Lock.tryLock()方法尝试对lock对象加锁并返回一个boolean值,如果成功了,返回true,表明当前没有别的线程在使用打印机,那么当前线程将获得lock对象的锁,并继续打印;如果失败了,返回false,表明别的线程正在使用打印机,当前线程将简单的返回,而不是等待别的线程释放锁。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值