线程同步

小凤凤是我 2014-08-22 03:30:10
public class CopyOfTestSys1 extends Thread {
Timer t=new Timer();
public static void main(String[] args) {
Thread thread1=new CopyOfTestSys1();
Thread thread2=new CopyOfTestSys1();
thread1.start();
thread2.start();
}

@Override
public void run() {

t.add(Thread.currentThread().getName());

}

}

public class Timer {
private static int number=0;
//synchronized {};
public synchronized void add(String name){

number++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( number );

}


}
...全文
178 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
tyilack_小小黑 2014-08-22
  • 打赏
  • 举报
回复
用Timer类去实现Runnable接口吧
skgary 2014-08-22
  • 打赏
  • 举报
回复

 
public class Timer {
     private static int number=0;
    private static Object lock = new Object();
     public void  add(String name){
synchronized (lock){
     number++;
     try {
        Thread.sleep(1);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
   System.out.println( number  );
 }
 } 
    
   
 } 
码上行动_Light 2014-08-22
  • 打赏
  • 举报
回复
同上面各位同学:两个Timer是无法实现同步的。改为如下:
public class CopyOfTestSys1 extends Thread {
    private Timer t;
 
    CopyOfTestSys1(Timer t){
        this.t = t;
    }
    public static void main(String[] args) throws InterruptedException {
        Timer tt = new Timer();
        Thread thread1 = new CopyOfTestSys1(tt);
        Thread thread2 = new CopyOfTestSys1(tt);
        thread1.start();
        thread2.start();
    }
 
    @Override
    public void run() {
        t.add(Thread.currentThread().getName());
    }
 
}

public class Timer {
     private static int number=0;
     public synchronized void  add(String name){
     number++;
     try {
        Thread.sleep(1);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
   System.out.println( number  );

 } 
   
  
 } 
一大三千 2014-08-22
  • 打赏
  • 举报
回复
改成这样:
Thread thread1 = new CopyOfTestSys1(t);
 Thread thread2 = new CopyOfTestSys1(t);
rockets311 2014-08-22
  • 打赏
  • 举报
回复
你的写法创建了两个Timer对象,怎么可能同步?
public class CopyOfTestSys1 extends Thread {
	private Timer t;

	CopyOfTestSys1(Timer t){
		this.t = t;
	}
	public static void main(String[] args) throws InterruptedException {
		Timer tt = new Timer();
		Thread thread1 = new CopyOfTestSys1(tt);
		Thread thread2 = new CopyOfTestSys1(tt);
		thread1.start();
		thread2.start();
	}

	@Override
	public void run() {
		t.add(Thread.currentThread().getName());
	}

}
rumlee 2014-08-22
  • 打赏
  • 举报
回复
你的synchronized是加在this,也就是当前对象上的。而你两个线程中创建了两个不同的Timer对象。 同步当然没有效果了。
小凤凤是我 2014-08-22
  • 打赏
  • 举报
回复
同步关键字不起作用

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧