首页 > 代码库 > Multi-Thread 1: how to use synchronized

Multi-Thread 1: how to use synchronized

1. synchronized

If two threads are using the same function( here we use output to print out string) of another instance, if we want to make sure that these two threads are not disturbing each other.

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();
		}
	}

}

If code won‘t escape disturbing each other.
The calling function must be the same one from the same instance!

 Error Example 1:

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();

if we use new outputer.output("bbbbbbbbb"), still won‘t work. since the two threads are calling different function from two different instance.So one thing is clear that we have to add synchronized key word and it should be added to the same Instance.

ANSWER 1:
we can make it possible by letting two threads calling for the same function, of the same Instance  so we can change the output function to:

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

ANSWER 2: 
Since we already know the key point is to make the same Instance be synchronized, so we can make the two threads call fordifferent functions( output1, and output3), as long as the instance is synchronized(which is also easy to do: both of the two functions should addsynchronized key word)

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();
}

ANSWER 3:  in the case that the function is a static method
If the method is a static method, since static method is initialized before Instance, if we still want to synchronize two method, One way is to make both of the two methodstatic synchronized, another way, we can synchronize on the instance‘s class 

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();
}