在两个线程之间共享变量 [英] share variables between two thread

查看:239
本文介绍了在两个线程之间共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我是Java多线程的新手
我必须线程化,并且我想在两个线程之间共享两个变量(x,y),一个线程向变量添加数字,而另一个线程打印变量值,我该怎么做?
谢谢

public class First{
int x,y;
publi First(){
x=0;
y=0;
}
public void doIt(){
Thread t1=new Thread(new Second());
t1.start;
System.out.println("x is:"+x,"y is:"+y);
}
}
class Second implements Runnable{

private void increment(int x,int y){
x++;
y++;
}
public void run(){
increment(First.x,First.y);
}
}

解决方案

从技术上讲,使用由两个或更多线程共享的类成员的所有操作就是 lock .请参阅:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html [ http://en.wikipedia.org/wiki/Race_condition [ ^ ].这只是一个技术术语.我曾经通过使用不同的,更确定的术语"执行顺序的不正确依赖项"来倾斜这种现象.就是这样.

在此示例中,尽管有正确的线程同步,但是代码的输出还是无法预测的:有时主线程可能会打印增量值,有时会打印非增量值,因为没有任何东西可以保证对共享内存的任何特定操作顺序:有时可以打印并稍后增加,有时它可以增加然后打印. (但是,这些变体可能具有非常不同的概率;这是竞态条件的危险:程序可以按预期的顺序工作数百万次,但最终会以破坏其目的的方式更改顺序.)

我希望这段代码的唯一目的就是:演示比赛条件.使用线程执行此类任务没有任何实际意义.

—SA


hi i am newbie to multithread in java
i have to thread and i want to share two varibles(x,y) between two thread that one thread adds a number to variables and another thread prints variable value,how can i do it?
thanks

public class First{
int x,y;
publi First(){
x=0;
y=0;
}
public void doIt(){
Thread t1=new Thread(new Second());
t1.start;
System.out.println("x is:"+x,"y is:"+y);
}
}
class Second implements Runnable{

private void increment(int x,int y){
x++;
y++;
}
public void run(){
increment(First.x,First.y);
}
}

解决方案

Technically speaking, all you need to work with class members shared by two or more thread is lock. Please see:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html[^].

This task is interesting by the reason not directly related to the techniques of thread synchronization, but due to its effect on semantic. This is classical example of race condition, see http://en.wikipedia.org/wiki/Race_condition[^]. This is just a technical term. I used to lean about this phenomenal with the use of different, more definitive term "incorrect dependency of the order of execution". This is exactly what it is.

In this example, the output of the code in unpredictable, despite of correct thread synchronization: sometimes main thread may print incremented, sometimes non-incremented values, because nothing guarantees any certain order of the operation on the shared memory: sometimes can print and later increment, sometime it can increment and then print. (However, these variants could come with very different probabilities; this is a danger of race conditions: a program may work millions of time in expected order but eventually change the order the way it defeats its purpose.)

I hope the sole purpose of this code would be exactly this: to demonstrate race condition. This is no any practical sense in using threads for such tasks.

—SA


这篇关于在两个线程之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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