字符串缓冲区线程安全

时间:2018-10-08 16:29:54

标签: java stringbuffer

StringBuffer在Java中是线程安全的,这意味着它提供对多个线程的同步访问。但是当我运行下面的代码时,它的运行方式与同步块中的方式不同。 / p>

class Hackerearth{
    static StringBuffer s = new StringBuffer("String Buffer Multithreading test");
    public static void main(String args[] ) throws Exception {
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                Thread1();
            }
        });
        Thread t2 = new Thread(new Runnable(){
            public void run(){
                Thread2();
            }
        });
        t1.start();
        t2.start();
    }


    public static void Thread1(){
        for(int i = 0; i < s.length(); i++){
            s.setCharAt(i, ((char) ((int) (Math.random() * 26) + 97)));
            System.out.println("Thread is: " + Thread.currentThread().getName() + ".S is: " + s);
            if(i == s.length() - 1){
                try {
                    Thread.sleep(2000);
                    s = new StringBuffer("String Buffer Multithreading test");
                } catch (InterruptedException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }

    }

    public static void Thread2(){
        for(int i = 0; i < s.length(); i++){
            s.setCharAt(i, ((char) ((int) (Math.random() * 26) + 97)));
            System.out.println("Thread is: " + Thread.currentThread().getName() + ".S is: " + s);
            if(i == s.length() - 1){
                try {
                    Thread.sleep(2000);
                    s = new StringBuffer("String Buffer Multithreading test");
                } catch (InterruptedException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }

}

0 个答案:

没有答案