我正在尝试使用 2 个线程按顺序打印 1 到 10。
这是代码。
public class Multithreading implements Runnable {
private static volatile Integer count = 1;
private static volatile String threadId = "1";
Object object = new Object();
@Override
public void run() {
try {
while (count <= 10) {
synchronized (object) {
if(!Thread.currentThread().getName().equals(threadId)) {
object.wait();
}
else {
System.out.println(Thread.currentThread().getName()+" "+ count);
count++;
if(threadId.equals("1"))
threadId = "2";
else threadId = "1";
object.notifyAll();
}
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Multithreading t1m = new Multithreading();
Multithreading t2m = new Multithreading();
Thread t1 = new Thread(t1m);
Thread t2 = new Thread(t2m);
t1.setName("1");
t2.setName("2");
t1.start();
t2.start();
}
}
但是两个线程在打印第一个线程打印 1 后都会等待。
我正在尝试为没有嵌套内部类的两个线程实现这个3线程按顺序打印数字解决方案。任何帮助将不胜感激。
使用原子整数,
public class PrintNumber implements Runnable {
private static AtomicInteger num = new AtomicInteger(0);
private static final int MAX = 100;
@Override
public void run() {
while (num.get() < MAX) {
System.out.println(Thread.currentThread().getName() + " --- " + num.incrementAndGet());
}
}
public static void main(String[] args) {
Thread t = new Thread(new PrintNumber());
Thread t2 = new Thread(new PrintNumber());
t.start();
t2.start();
}
}