在这篇文章中,我们将看到如何在 java 中使用 3 个线程打印序列。
你 3 个线程。您需要使用这 3 个线程来打印序列。您需要以自然顺序打印到 MAX。
例如: 假设您有 3 个线程。T1、T2 和 T3。 如果 MAX 为 10,则需要打印:
T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10
解决方案
我们将在这里使用余数的概念。
-
如果 number%3==1 则 T1 将打印数字并增加它,否则将进入等待状态。
-
如果 number%3==2 则 T2 将打印该数字并增加它,否则将进入等待状态。
-
如果 number%3==0 则 T3 将打印该数字并增加它,否则将进入等待状态。
让我为它提供一个简单的程序。 让我们创建一个名为“PrintSequenceRunnable”的类,它将实现 Runnable 接口。
public class PrintSequenceRunnable implements Runnable{
public int PRINT_NUMBERS_UPTO=10;
static int number=1;
int remainder;
static Object lock=new Object();
PrintSequenceRunnable(int remainder)
{
this.remainder=remainder;
}
@Override
public void run() {
while (number < PRINT_NUMBERS_UPTO-1) {
synchronized (lock) {
while (number % 3 != remainder) { // wait for numbers other than remainder
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + number);
number++;
lock.notifyAll();
}
}
}
}
让我们创建一个名为“PrintThreadsSequentiallyMain”的类,它将实现Runnable接口
public class PrintThreadsSequentiallyMain {
public static void main(String[] args) {
PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);
Thread t1=new Thread(runnable1,"T1");
Thread t2=new Thread(runnable2,"T2");
Thread t3=new Thread(runnable3,"T3");
t1.start();
t2.start();
t3.start();
}
}
当你运行上面的程序时,你会得到下面的输出。
T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10
这就是在 java 中使用 3 个线程打印线程的全部内容。
|