在多线程中,同一份资源在多个线程中都用了,可能会死锁,因为大家都不释放,举个例子:
- public class Lockup {
- public static void main(String[] args) {
-
- Object m = new Object();
- Object g = new Object();
-
- Test t1 = new Test(g,m);
- Test2 t2 = new Test2(g,m);
-
- Thread th1 = new Thread(t1);
- Thread th2 = new Thread(t2);
-
- th1.start();
- th2.start();
-
- }
-
- }
- class Test implements Runnable{
- Object goods ;
- Object money ;
-
-
-
- public Test(Object goods, Object money) {
- super();
- this.goods = goods;
- this.money = money;
- }
- @Override
- public void run() {
-
- while(true){
- test();
- }
-
- }
-
- public void test(){
- synchronized(goods){
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized(money){
-
- }
- }
- System.out.println("一手给钱");
- }
-
- }
- class Test2 implements Runnable{
- Object goods ;
- Object money ;
-
-
-
- public Test2(Object goods, Object money) {
- super();
- this.goods = goods;
- this.money = money;
- }
- @Override
- public void run() {
-
- while(true){
- test();
- }
-
- }
-
- public void test(){
- synchronized(money){
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized(goods){
-
- }
- }
- System.out.println("一手给货");
- }
-
- }
复制代码
|
|