synch.java

来自「nanjing university cs 的java课件。 对新手很有用。付」· Java 代码 · 共 43 行

JAVA
43 行
字号
class Callme {
	void call(String msg) { 
		System.out.print("["+msg); 
		try{ 
			Thread.sleep(2000); 
		}
		catch (Exception e){
		} 
		System.out.println("]"); 
	}      
}

class Caller implements Runnable{ 
	String msg;		
	Callme target;
	        
	public Caller(Callme t, String s){ 
		target=t; 
		msg=s; 
		//new Thread(this).start();
	}
	
	public void run(){     
		//target.call(msg);
		synchronized(target){
        	target.call(msg); 
        }               
	}
} 	 //[1][2][3] expected

public class Synch {      
	public static void main(String args[]) {      
	Callme target = new Callme(); 
	//new Caller(target,"1");
	//new Caller(target,"2"); 
	//new Caller(target,"3"); 
	
	new Thread(new Caller(target,"1")).start();
	new Thread(new Caller(target,"2")).start();
	new Thread(new Caller(target,"3")).start();
	}  
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?