Java中的多线程同步 [英] multi-thread synchronization in Java

查看:77
本文介绍了Java中的多线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test {

	public static void main(String[] args) {

		for(int i=0; i<5; i++) {
			ThreadEX ex = new ThreadEX();
			new Thread(ex).start();
		}
		
	}

}

class ThreadEX implements Runnable {

	private static Hashtable<Integer, String> table;
	private boolean thCheck = false;
	
	public ThreadEX() {
		table = new Hashtable<Integer,String>();
	}
	
	public void run() {
		synchronized(this) {
			table.put(this.hashCode(), "tmp");		
			System.out.println(this.hashCode() + " added, size : " + table.size());
		}
	}
}



大家好.
我想问一下Java中的多线程同步.
上面有一个代码,我以它为例.
我除外,它将产生如下结果:

添加了6413875,大小:1
添加5442986,大小:2
添加了28737396,大小:3
添加的827574,大小:4
添加了24355087,大小:5

(哈希码无关紧要).

但是,它根本不存在.我认为我在同步哈希表时遇到问题,但是我不知道现在出了什么问题.

有人可以给我任何建议或更正我的同步代码,以使结果如我所料吗?

谢谢!



Hello, everyone.
I like to ask about multi-thread synchronization in Java.
There is a code above, which I used as an example.
I excepted it would make a result like this:

6413875 added, size : 1
5442986 added, size : 2
28737396 added, size : 3
827574 added, size : 4
24355087 added, size : 5

(hash code doesn''t matter).

However, it doesn''t at all. I think I have a problem with synchronizing hashtable, but I don''t know what the wrong is for now.

Could you anyone give me any advice or correction of my synchronization code, to make a result like what I excepted?

Thank you!

推荐答案

您已经写了:
synchronized(this) {

但是所有线程中的this指向ThreadEX类的另一个实例

您可以执行以下操作之一:
1.用这样的方式写:synchronized(ThreadEx.class) {
2.使用ConcurrentHashTable类.

另外,您在每个线程中重新初始化table.您绝对应该解决此问题.
我对您的版本进行了略微更改:

You have written:
synchronized(this) {

But this in all thread points to a different instance of your ThreadEX class

You can do one of the following:
1. Write in such way: synchronized(ThreadEx.class) {
2. Use ConcurrentHashTable class.

Also, you re-initialize table in each thread. You should definitely fix this.
I have slightly changed your version:

public class ThreadEX implements Runnable {
	private static Hashtable<Integer, String> table = new Hashtable<Integer,String>();
	private boolean thCheck = false;
	
	public ThreadEX() {
	}
	
	@Override
	public void run() {
		synchronized(ThreadEX.class) {
			table.put(this.hashCode(), "tmp");		
			System.out.println(this.hashCode() + " added, size : " + table.size());
		}
	}
}



祝你好运!



Good luck!


这篇关于Java中的多线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆