java 线程中suspend,resume方法独占

  • Post author:
  • Post category:java


在使用suspend与resume方法是, 如果使用不当, 极易造成公共的同步对象的独占, 使得其他的线程无法访问公共的同步对象。

如:

package com.mjlf.myBatis.thread;

/**
 * Created by a123 on 17/2/9.
 */
public class ThreadSuspendTest {
    public synchronized void printString(){
        System.out.println("begin");
        if(Thread.currentThread().getName().equals("a")){
            System.out.println("Thread a will suspend");
            Thread.currentThread().suspend();
        }
        System.out.println("end");
    }

    public static void main(String[] args){
        try{
            final ThreadSuspendTest threadSuspendTest = new ThreadSuspendTest();
            Thread thread1 = new Thread(new Runnable() {
                public void run() {
                    threadSuspendTest.printString();
                }
            });
            thread1.setName("a");
            thread1.start();


            Thread thread2 = new Thread(new Runnable() {
                public void run() {
                    System.out.println("B线程启动了, 但是无法进入printString方法中");
                    System.out.println("因为printString()方法陪线程a锁定并且永远suspend暂停了");
                    threadSuspendTest.printString();
                }
            });
            thread2.setName("B");
            thread2.start();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

/*
begin
Thread a will suspend
B线程启动了, 但是无法进入printString方法中
因为printString()方法陪线程a锁定并且永远suspend暂停了

*/

线程a启动后进入同步代码pringString放中被suspend暂停后,线程B将永远无法进入该方法。

同时需要注意的是System.out.println()方法与suspend方法结合使用的陷阱, 因为println()方法也是一个同步方法, 如果在执行该方法的时候被suspend后, 则其他地方将无法使用该方法

如:

package com.mjlf.myBatis.thread;

/**
 * Created by a123 on 17/2/9.
 */
public class ThreadSuspendTest2 {
    static int i = 0;

    public static void main(String[] args) {
        try{
        Thread thread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    i++;
                    System.out.println(i);
                }
            }
        });

        thread.start();
        thread.sleep(1000);
        thread.suspend();
        System.out.println("end");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}



版权声明:本文为mjlfto原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。