I am trying to print number 1 to 31 In order with Three Threads. When the number became 31, I want to output "(current Thread) defeated." Also the number can be output up to 3.
So I want to output like
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
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. But it prints only "Thread One output defeat" I don't know what is problem. 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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.