如何使用多线程的全局变量 [英] How to use global variables with multiple threads

查看:105
本文介绍了如何使用多线程的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道究竟是什么造成了这种情况。我认为不应该有任何竞争条件,但无论我运行我的程序多少次,我的全局变量总是不一致。



I don't know what's exactly causing this. I think there shouldn't be any race condition, yet my global variable is always inconsistent no matter how many time I run my program.

public class main{


	public static int global;




	public static void main(String[] args){

			Girls [] girls = new Girls[10];


			Guys [] guys = new Guys[10];

			for(int i = 0; i < 10; i++)
			{


				girls[i] = new Girls();
				guys[i] = new Guys();

			}


			for(int i = 0; i < 10; i++)
			{

				girls[i].start();

				guys[i].start();



			}




			for(int i = 0; i < 10; i++)
			{
				try{



					girls[i].join();
					guys[i].join();



				} catch(InterruptedException e){
					System.out.println("exc caught");
				}


			}


	}
}







public class Guys extends Thread{



		public static void go()throws InterruptedException{

			final Lock lock = new ReentrantLock();



			lock.lock();


			System.out.println("global " + main.global);



			main.global = main.global + 100;

			lock.unlock();


		}






	public void run(){

		try{

		FileControl2 fic = new FileControl2();


			for(int i = 0; i <1; i++)
			{
				System.out.println(this);


				fic.GuysEntry();

				go();

				fic.GuysExit();

			}
		} catch(InterruptedException e)
		{
			System.out.println("Interrupted Exception caught");
		}

	}


}







public class FileControl2 {

	final Lock lock = new ReentrantLock();
	final Condition guys = lock.newCondition();
	final Condition girls = lock.newCondition();
	int nGirls = 0;
	int nGuys = 0;



	public void GuysEntry()throws InterruptedException{
		lock.lock();
		try{
			if(nGirls > 0)
			{
				guys.await();
			}
			nGuys++;




		   }
		finally{
			lock.unlock();
		}


	}



	public void GuysExit()throws InterruptedException{
		lock.lock();
		try{
			girls.signal();
			nGuys--;

		}
		finally{

			lock.unlock();
		}

	}


	public void GirlsEntry()throws InterruptedException{
		lock.lock();
		try{

			if(nGuys > 0)
			{
				girls.await();
			}
			nGirls++;


		}
		finally{

			lock.unlock();
		}

	}

	public void GirlsExit()throws InterruptedException{
		lock.lock();
		try{
			guys.signal();
			nGirls--;

		}
		finally{
			lock.unlock();
		}

	}


}





我期望的产出是全球100全球200全球300全球400全球500全球600全球700全球800全球900全球1000
$ b但我得到全球100全球100全球100全球200全球200全球600全球200



The output I expect is global 100 global 200 global 300 global 400 global 500 global 600 global 700 global 800 global 900 global 1000

but I get something like global 100 global 100 global 100 global 200 global 200 global 600 global 200

推荐答案

请参阅: http://en.wikipedia.org/wiki/Mutual_exclusion [ ^ ]。



-SA


在.NET网络中,没有诸如全局变量之类的东西。它没有改变任何东西。重要的方面不是全局,而是在线程之间共享任何对象的事实。



正如我已经解释的那样,应该尽量减少对象的共享。您应该尝试在堆栈上进行大多数计算,当然,每个线程意味着使用单独的堆栈。 最好的同步是没有同步。



现在,对于共享对象,这是一个简单的模式,它可以在没有竞争条件和死锁的情况下工作:所有对锁的保护对共享对象的访问,同一个具有相同锁的共享对象,锁应该严格嵌套(一个最简单的嵌套违规是同时最简单的教科书死锁示例之一)。在互斥区域内抛出任何异常的情况下释放锁并保留严格的嵌套非常重要。



请再次查看我最近的所有链接回答:

这是否足够确保相互排斥? [ ^ ]。



你需要以更严肃,规律和根本的方式全部采取这一切,然后再尝试你的问题。您需要在良好的水平上学习整个主题并定期进行自我教育。



-SA
In .NET net, there is no such thing as "global variable". It does not change anything. The important aspect is not "global", but the fact you share any objects between threads.

As I already explained, sharing of objects should be minimized. You should try to do the most calculations on stack, as, of course, each thread means using a separate stack. The best synchronization is no synchronization.

Now, with shared objects, this is the simple pattern which works without race conditions and deadlocks: all access to shared object is guarded by the lock, same shared object with the same lock, locks should be strictly nested (one simplest violation of nesting is at the same time one of the simplest "textbook" example of a deadlock). It is important to release the lock and preserve strict nesting in the case of any exception thrown inside the mutual exclusion area.

Please see again, all links a in my recent answer:
Is this enough to insure mutual exclusion?[^].

You need to take it all in more serious, regular and fundamental way then you are trying to do with your questions. You need to learn the whole topic on good level and educate yourself on a regular basis.

—SA

这篇关于如何使用多线程的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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