[英]How to print number 1 to 31 with three threads in JAVA?
I am trying to print number 1 to 31 In order with Three Threads.我正在尝试使用三个线程按顺序打印数字 1 到 31。 When the number became 31, I want to output "(current Thread) defeated."当数字变为 31 时,我要将 output “(current Thread) 打败。” Also the number can be output up to 3.也可以是 output 最多 3 个。
So I want to output like所以我想像 output
Thread One print: 1 2 Thread Two print: 3 4 5 Thread Three print: 6 7 Thread One print: 8...... Thread Three print: 31 Thread Three defeat线程一印:1 2 线程二印:3 4 5 线程三印:6 7 线程一印:8…… 线程三印:31 线程三败
and program ends.程序结束。
public class MyRunnable implements Runnable {
Stack sta = new Stack();
public void run() {
while(sta.getStack()<=31){
int stack = 1;
stack++;
sta.setStack(stack);
System.out.println(Thread.currentThread().getName() + "print: "+ stack);
}
}
}
////////////
public class Stack {
private int stack = 1;
public synchronized void setStack (int stack) {
for(int cnt = 1; cnt<=31; cnt ++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + "defeated.");
}
}
public int getStack() {
return this.stack;
}
}
////////////////////
public class ThreadTest {
public static void main(String[] args) {
Runnable threadRun = new MyRunnable();
Thread myThread1 = new Thread(threadRun);
Thread myThread2 = new Thread(threadRun);
Thread myThread3 = new Thread(threadRun);
myThread1.setName("Thread One");
myThread2.setName("Thread Two");
myThread3.setName("Thread Three");
myThread1.start();
myThread2.start();
myThread3.start();
}
}
I made 3 classes.我上了3节课。 But it prints only "Thread One output defeat" I don't know what is problem.但它只打印“Thread One output defeat”我不知道是什么问题。 It won't print Thread in order.它不会按顺序打印线程。 I'm not good at using this platform so sorry for looking weird.我不擅长使用这个平台,所以很抱歉看起来很奇怪。
I tried a bit and came up with this:我试了一下,想出了这个:
public class MyRunnable implements Runnable {
Stack sta = new Stack();
@Override
public void run() {
while (sta.getStack() <= 31) {
int stack = sta.getStack() + 1;
sta.setStack(stack);
if (stack <= 31) {
System.out.println(Thread.currentThread().getName() + " print: " + stack);
}
}
}
}
public class Stack {
private int stack = 0;
public synchronized void setStack(int stack) {
this.stack = stack;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (stack > 31) {
System.out.println(Thread.currentThread().getName() + " defeated.");
}
}
public synchronized int getStack() {
return this.stack;
}
}
public class ThreadTest {
public static void main(String[] args) {
Runnable threadRun = new MyRunnable();
Thread myThread1 = new Thread(threadRun);
Thread myThread2 = new Thread(threadRun);
Thread myThread3 = new Thread(threadRun);
myThread1.setName("Thread One");
myThread2.setName("Thread Two");
myThread3.setName("Thread Three");
myThread1.start();
myThread2.start();
myThread3.start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.