Home >Java >javaTutorial >What impact does synchronized method have on non-synchronized method?
StringBuilder is a thread-unsafe class.
StringBuffer is thread-safe because the methods in it are synchronized.
I wrote a piece of code today to test it: use a loop to open 10 threads, and call the append of StringBuffer (StringBuilder) to add 1 to 10.
The results are expected to be the same: thread-unsafe StringBuilder will miss some numbers,
public static void main(String[] args) throws InterruptedException { StringBuffer buffer = new StringBuffer(); StringBuilder builder = new StringBuilder(); // 开启十个线程,分别对buffer 和 builder 操作 for(int i = 0; i < 10; i++) { int j = i; new Thread(new Runnable() { public void run() { try { Thread.sleep(500); //造成阻塞 } catch (InterruptedException e) { e.printStackTrace(); } builder.append(j); } }).start(); } //等待以上操作完成 Thread.sleep(1000); // 打印结果 System.out.println("builder:"+builder); }
Thread-safe StringBuffer Then all 10 numbers are appended:
public static void main(String[] args) throws InterruptedException { StringBuffer buffer = new StringBuffer(); StringBuilder builder = new StringBuilder(); // 开启十个线程,分别对buffer 和 builder 操作 for(int i = 0; i < 10; i++) { int j = i; new Thread(new Runnable() { public void run() { try { Thread.sleep(500); //造成阻塞 } catch (InterruptedException e) { e.printStackTrace(); } buffer.append(j); } }).start(); } //等待以上操作完成 Thread.sleep(1000); // 打印结果 System.out.println("buffer:"+buffer); }
At this time: If I operate the builder and buffer at the same time, Let’s first call the buffer’s append. At this time, because the builder and the buffer are in the same thread, the builder’s method is turned into a “synchronized” method because the buffer blocks the thread. 10 numbers are also appended
public static void main(String[] args) throws InterruptedException { StringBuffer buffer = new StringBuffer(); StringBuilder builder = new StringBuilder(); // 开启十个线程,分别对buffer 和 builder 操作 for(int i = 0; i < 10; i++) { int j = i; new Thread(new Runnable() { public void run() { try { Thread.sleep(500); //造成阻塞 } catch (InterruptedException e) { e.printStackTrace(); } buffer.append(j); builder.append(j); } }).start(); } //等待以上操作完成 Thread.sleep(1000); // 打印结果 System.out.println("buffer:"+buffer); System.out.println("builder:"+builder); }
The above is the detailed content of What impact does synchronized method have on non-synchronized method?. For more information, please follow other related articles on the PHP Chinese website!