任务,当我试图使用打印ABC反复使用三个线程无限次数 我的代码是多线程在Java中使用3个一线
package javap;
public class Pattern {
volatile int status=1;
public static void main(String[] args) {
Pattern p = new Pattern();
A1 a=new A1(p);
B1 b=new B1(p);
C1 c=new C1(p);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
Pattern p1;
A1(Pattern p){
this.p1 = p;
}
@Override
public void run() {
try{
synchronized (p1) {
for (int i = 0; i < 100; i++) {
while(p1.status!=1){
p1.wait();
}
System.out.print("A ");
p1.status = 2;
p1.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
Pattern p2;
B1(Pattern p2){
this.p2 = p2;
}
@Override
public void run() {
try{
synchronized (p2) {
for (int i = 0; i < 100; i++) {
while(p2.status!=2){
p2.wait();
}
System.out.print("B ");
p2.status = 3;
p2.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
Pattern p3;
C1(Pattern p){
this.p3 = p;
}
@Override
public void run() {
try{
synchronized (p3) {
for (int i = 0; i < 100; i++) {
while(p3.status!=3){
p3.wait();
}
System.out.print("C ");
p3.status = 1;
p3.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 3 :"+e.getMessage());
}
}
}
打印ABC(;;)或同时(真)我的ide挂起,我nt得到任何输出 ,所以我限制它100次。 有无论如何,我可以让这个运行无数次。
在此先感谢
'为(;;的System.out.println())Stream.of( “A”, “B”, “C” ).parallel()forEachOrdered(的System.out ::打印);' –
我应该repllace所有与此@elliott弗里希 – aish
将取代你写的一切循环。它并行打印“a”,然后“b”,然后“c”,然后打印一个换行符并循环。 –