Thread 中的同步方法设置

Turths 发布于 2016/09/27 11:20
阅读 182
收藏 0
package HomeWork;

public class ConsoleWriter {
public synchronized void writeToConsole(String p){
for (int i=0;i<9;i++){
		System.out.println("当前线程的名字"+Thread.currentThread().getName()+"参数字符串的内容为"+p);
		try{
			Thread.sleep(1000);
		}catch(InterruptedException e){}
	}
System.out.println("方法WTC结束");
}}



package HomeWork;

public class MyWriter extends Thread{
	private String name;
	private ConsoleWriter cw;
	public MyWriter(ConsoleWriter cw, String name) {
	super(name);
	this.cw=cw;
	
	}

	public void run(){
		ConsoleWriter cw=new ConsoleWriter();
		cw.writeToConsole("Hello,my friend!");
	}

}




package HomeWork;

public class use {
public static void main(String[] args){
	ConsoleWriter cw=new ConsoleWriter();
	MyWriter thread1=new MyWriter(cw,"线程1");
	MyWriter thread2=new MyWriter(cw,"线程2");
	thread1.start();
	thread2.start();
	
}
}



已经在ConsoleWriter 的writerToConsole()方法中输入修饰符synchronized 为什么运行后没有任何效果?两个线程还是同时执行了.            



加载中
0
逝水fox
逝水fox
把run()中的ConsoleWriter cw=newConsoleWriter();删掉
T
Turths
感谢
返回顶部
顶部