public class TraditionalThreadSynchronize { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new TraditionalThreadSynchronize().initial(); } private void initial(){ final Outputter outputter = new Outputter(); new Thread(new Runnable(){ //this is the first theread public void run(){ while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputter.output("aaaaaaaaaaa"); //the thread want to use outputer print a string. } } }).start(); new Thread(new Runnable(){//thread two public void run(){ while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputter.output("bbbbbbbbbbbbb"); //thread two also want to use the function to print } } }).start(); } class Outputter{ public void output(String name){ int len = name.length(); for(int i= 0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); } } }
new Thread(new Runnable(){ @Override public void run() { while(true){ try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } new outputer.output("bbbbbbbb"); } } }).start();
public synchronized void output(String name){
int len = name.length();
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
// Synchronized add to the function is the same as synchronized(this). the Instance is sychronized for this function
public void output(String name){ int len = name.length(); synchronized (this) { for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void output2(String name){ int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); }
public void output(String name){ int len = name.length();
synchronized (Outputer.class) { for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); }
System.out.println(); } }
public synchronized void output2(String name){ int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); }
Multi-Thread 1: how to use synchronized,布布扣,bubuko.com
Multi-Thread 1: how to use synchronized
原文:http://blog.csdn.net/liuhuan_tao/article/details/25760369