在java中使用三个线程打印111222333
我使用join方法打印序列在java中使用三个线程打印111222333,java,Java,我使用join方法打印序列 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"); Th
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();
}
}
公共类SequencePrint{
公共静态void main(字符串[]args)引发InterruptedException{
Runnable r1=新的打印顺序(“1”);
Runnable r2=新的PrintSeq(“2”);
Runnable r3=新的打印顺序(“3”);
螺纹t1=新螺纹(r1);
螺纹t2=新螺纹(r2);
螺纹t3=新螺纹(r3);
t1.start();
t1.join();
t2.start();
t2.连接();
t3.start();
t3.join();
System.out.println(“主”);
}
}
类PrintSeq实现Runnable{
私有字符串seq=null;
公共打印顺序(字符串顺序){
this.seq=seq;
}
@凌驾
公开募捐{
对于(inti=0;i我想下面的内容将对您有所帮助。它使用wait/notify
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();
}
}
公共类SequencePrint{
静态int数据=1;
静态最终整数序列计数=3;
公共静态类辅助程序实现可运行{
私有int-id;
私有对象锁=null;
@凌驾
公开募捐{
int c=0;
已同步(锁定){
试一试{
while(id!=数据){
lock.wait();
}
而(c
您的标题显示每个字符串重复三次。您的问题是四次。您的代码重复10次。一致性对于清晰性很重要。您对您的方法不满意的地方是什么?我需要使用等待通知或阻塞队列打印序列