我已经实现了两个线程,一个用于打印整数,另一个用于打印英文字母。线程应该串联工作。
我使用了一个synchronized块,一次只有一个线程会持有锁。但不知何故,AtomicInteger没有按预期工作。一个线程对count变量的更改对其他不同的线程不可见。怎么可能。我错过了什么吗?
我的实施
package com.concurrency;
import java.util.concurrent.atomic.AtomicInteger;
公共类ThreadWaitEg {
// Single monitor object for both threads
private final Object monitor = new Object();
// Thread-safe counter for both threads
private final AtomicInteger count = new AtomicInteger(0);
private class PrintNumber implements Runnable
{
@Override
public void run()
{
for (int i = 0; i < 26; i++)
{
synchronized (monitor)
{
System.out.println("From PrintNumber "+count.get());
try
{
while ((count.get()) % 2 != 0)
{
monitor.wait();
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(i);
count.getAndIncrement();
monitor.notifyAll();
}
}
}
}
private class PrintChar implements Runnable
{
@Override
public void run()
{
for (int charr = 'A'; charr <= 'Z'; charr++)
{
synchronized (monitor)
{
System.out.println("From PrintChar "+count.get());
try
{
while ((count.get()) % 2 == 0)
{
monitor.wait();
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println((char) charr);
count.getAndIncrement();
monitor.notifyAll();
}
}
}
}
public static void main(String[] args)
{
System.out.println("from main thread");
Runnable runInt = new ThreadWaitEg().new PrintNumber();
new Thread(runInt).start();
Runnable runChar = new ThreadWaitEg().new PrintChar();
new Thread(runChar).start();
System.out.println(" main thread completes ");
}
}
输出
来自主线程
来自PrintNumber 0
0
来自PrintNumber 1
主线完成
来自PrintChar 0
答案 0 :(得分:0)
你的主要问题是你创建了主ThreadWaitEg类的两个实例 - 每个实例都有自己的&#34;监视器&#34;和&#34;计数&#34;对象,因此两个线程之间不共享对象。最快的解决方法是只创建一个实例,即将main()方法替换为:
public static void main(String[] args) {
System.out.println("from main thread");
ThreadWaitEg threadWaitEg = new ThreadWaitEg();
Runnable runInt = threadWaitEg.new PrintNumber();
new Thread(runInt).start();
Runnable runChar = threadWaitEg.new PrintChar();
new Thread(runChar).start();
System.out.println(" main thread completes ");
}