java - 在java中使用三个线程打印111222333
问题描述
我使用连接方法打印序列。
public class SequencePrint {
public static void main(String[] args) throws InterruptedException {
Runnable r1 = new PrintSeq("1");
Runnable r2 = new PrintSeq("2");
Runnable r3 = new PrintSeq("3");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
System.out.println("Main");
}
}
class PrintSeq implements Runnable{
private String seq = null;
public PrintSeq(String seq) {
this.seq = seq;
}
@Override
public void run() {
for(int i=0 ; i<10 ; i++) {
System.out.print(seq);
}
System.out.println();
}
}
有没有办法在等待通知或其他同步技术中使用三个线程打印 111122223333。
解决方案
我想以下内容会对您有所帮助。它正在使用等待/通知。
public class SequencePrint {
static int data = 1;
static final int SEQ_COUNT = 3;
public static class Worker implements Runnable{
private int id;
private Object lock = null;
@Override
public void run() {
int c = 0;
synchronized (lock) {
try {
while(id != data) {
lock.wait();
}
while(c < SEQ_COUNT) {
c++;
System.out.print(id);
}
SequencePrint.data++;
lock.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public Worker(int x, Object lock) {
super();
this.id = x;
this.lock = lock;
}
}
public static void main(String args[]) {
Object lock = new Object();
Runnable r1 = new Worker(1, lock);
Runnable r2 = new Worker(2, lock);
Runnable r3 = new Worker(3, lock);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t1.start();
t2.start();
t3.start();
}
}
推荐阅读
- javascript - 如何在节点中导出 JS 模块
- python - 无法检查列表的长度,我想检查大于 0 的列表长度而不是遍历它并渲染每个元素
- mapbox - Mapbox GL-JS:为什么我在正常工作时会出现图像加载错误?
- r - 将特定文件夹移动到 R 中的新文件夹➡
- mongodb - 为什么 mongodump 执行 COLLSCAN?
- mysql - mysql没有读取整个文件,而是在使用“本地加载数据”时跳过行
- centos - 如何在 Centos 上安装 OctoberCMS?
- angular - Angular 2 和 Slim PHP 框架:如何正确转义字符串以在 GET 请求中使用
- jmeter - 如何在 JMeter 中插入请求之间的时间间隔?
- r - 如何识别列中多行的模式并使用 R 填充有关该模式的信息的新列?