java - Threads with shared integer object not working as expected
问题描述
I have a problem where i have to print the numbers in such format.
First 1
First 2
Second 3
Second 4
First 5
First 6
Second 7
Second 8
First 9
and so on...
I have implemented my runnable interface as below.
class ThreadDemo implements Runnable {
public volatile Integer num;
public Object lock;
public ThreadDemo(Integer num, Object lock) {
this.num = num;
this.lock = lock;
}
@Override
public void run() {
try {
while (true) {
int count = 0;
synchronized(lock) {
Thread.sleep(100);
while (count < 2) {
System.out.println(Thread.currentThread().getName() + " " + num++);
count++;
}
lock.notify();
lock.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
My main class is as follows
public class CoWorkingThreads {
private static volatile Integer num = new Integer(1);
public static void main(String...args) {
Object lock = new Object();
Thread thread1 = new Thread(new ThreadDemo(num, lock), "First");
thread1.start();
Thread thread2 = new Thread(new ThreadDemo(num, lock), "Second");
thread2.start();
}
}
when i run the program i am getting the output as follows
First 1
First 2
Second 1
Second 2
First 3
First 4
Second 3
Second 4
Instead of previously expected results. But when I Change the integer to atomic integer type i start getting the expected result. can anyone explain what is i can do to make it run with integer instead of using atomic integer
解决方案
Java Integer 不能通过引用传递。在您的代码中,每个线程都会创建变量的副本。但是 atomicInteger 可以通过引用传递。
此外,为了获得正确的结果,您可以将 num 变量更改为静态变量。
public static Integer num = 1;
public Object lock;
public ThreadDemo(Integer num, Object lock) {
//this.num = num;
this.lock =lock;
}
推荐阅读
- jquery - Rails - 在ajax之后使用部分更新引导弹出内容
- google-maps - 如何限制谷歌地图大小缩放不小于屏幕宽度/高度
- http - 误用的标头名称。... 带有 HttpResponseMessage 的响应标头,以及带有 HttpContent 对象的内容标头
- sql - 我应该为同一列中的字母和数字使用什么数据类型?
- elasticsearch - Elasticsearch Opendistro ISM:可以采取什么方法自动将翻转别名和策略应用于新索引?
- javascript - 从服务器(API?)获取数据并将其显示在 HTML 页面上
- python - 基于字符频率的字符串搜索
- flutter - 从 VSCODE 中的运行按钮运行测试时设置环境变量
- java - 设置闪烁文本的计时器
- python - Scipy.optimize 最小化“不兼容的不等式约束”