java中的多线程使用3个线程打印abc

时间:2017-04-03 03:45:44

标签: java multithreading synchronization

任务是使用三个线程无限次重复打印abc 我的代码是

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());
        }

    }
}

当我尝试使用for(;;)或while(true)时,我的ide挂起并且我没有得到任何输出 所以我把它限制在100次。 无论如何,我可以无限次地运行。

提前致谢

5 个答案:

答案 0 :(得分:1)

您的代码似乎很好。也就是说,你似乎编写了太多的代码来实现你的目标......考虑使用Executors.newFixedThreadPool(3)来创建你的3个线程并将它们放在一个池中。

ExecutorService service = Executors.newFixedThreadPool(3);

然后,将任务传递给池(可调用)

Future<String> resultA = service.submit(() -> {
    System.out.print("A ");
    return "A";
});

现在等待任务完成后再通过下一个任务:

resultA.get();

以下是完整的代码段:

public static void main(String[] args) throws ExecutionException, InterruptedException {

    ExecutorService service = Executors.newFixedThreadPool(3);
    int x = 0;
    while (x < 100) {
        service.submit(() -> {
            System.out.print("A ");
            return "A";
        }).get();

        service.submit(() -> {
            System.out.print("B ");
            return "B";
        }).get();

        service.submit(() -> {
            System.out.print("C ");
            return "C";
        }).get();

        x++;
    }

    service.shutdown();
}

那说你可以使用以下方法删除所有重复代码:

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService service = Executors.newFixedThreadPool(3);
        int x = 0;
        while (x < 100) {
            service.submit(getTask("A ")).get();
            service.submit(getTask("B ")).get();
            service.submit(getTask("C ")).get();
            x++;
        }

        service.shutdown();
    }

    private static Callable<String> getTask(String task) {
        return () -> {
            System.out.print(task);
            return task;
        };
    }
}

请注意,main不能抛出异常,但这应该是显而易见的。

另外,@ Elliott Frisch的答案很棒,因为它使用了JAVA 8并行流。
我认为你正在尝试学习Threads所以我的答案使用了Executors API,这使得线程相关的代码更简洁,更简洁。 / p>

应该熟悉Streams和Executors。

答案 1 :(得分:1)

我已经稍微修改了你的逻辑,并且输出流A B C的间隔为1000毫秒(更好的可视化)。

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) {
                while (true) {
                    while (p1.status != 1) {
                        try {
                            p1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    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) {
                while (true) {
                    while (p2.status != 2) {
                        try {
                            p2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    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) {
                while (true) {
                    while (p3.status != 3) {
                        try {
                            p3.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("C ");
                    Thread.sleep(1000);
                    p3.status = 1;
                    p3.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 3 :" + e.getMessage());
        }

    }
}
  

输出:A B C A B C A B C A B C A B C .....

答案 2 :(得分:0)

请尝试使用此代码

 package threadexample;

class A extends Thread{
Pattern writeAbcExample;

public A(Pattern writeAbcExample) {

    this.writeAbcExample = writeAbcExample;
}
@Override
public void run(){
    try{
        synchronized(writeAbcExample){
            while(true){
                while(writeAbcExample.status!=1){
                    try{
                    writeAbcExample.wait();
                    }catch(InterruptedException e){e.printStackTrace();}
                }
                System.out.println("A ");
                Thread.sleep(400);
                writeAbcExample.status=2;
                writeAbcExample.notifyAll();
            }
        }

    }catch(Exception e){e.printStackTrace();}
}

}


class B extends Thread{
Pattern writeAbcExample;

public B(Pattern writeAbcExample) {

    this.writeAbcExample = writeAbcExample;
}
@Override
public void run(){
    try{
        synchronized(writeAbcExample){
            while(true){
                while(writeAbcExample.status!=2){
                    try{
                    writeAbcExample.wait();
                    }catch(InterruptedException e){e.printStackTrace();}
                }
                System.out.println("B ");
                Thread.sleep(400);
                writeAbcExample.status=3;
                writeAbcExample.notifyAll();
            }
        }

    }catch(Exception e){e.printStackTrace();}
}

 }


class C extends Thread{
Pattern writeAbcExample;

public C(Pattern writeAbcExample) {

    this.writeAbcExample = writeAbcExample;
}
@Override
public void run(){
    try{
        synchronized(writeAbcExample){
            while(true){
                while(writeAbcExample.status!=3){
                    try{
                    writeAbcExample.wait();
                    }catch(InterruptedException e){e.printStackTrace();}
                }
                System.out.println("C ");
                Thread.sleep(400);
                writeAbcExample.status=1;
                writeAbcExample.notifyAll();
            }
        }

    }catch(Exception e){e.printStackTrace();}
}

 }
 public class Pattern {
 volatile int status=1;
  public static void main(String[] args) {
    Pattern writeAbcExample=new Pattern();
    new A(writeAbcExample).start();
    new B(writeAbcExample).start();
    new C(writeAbcExample).start();
  }

  }

答案 3 :(得分:0)

    public class PrintingABCUsingAtomicInteger {

        public static void main(String[] args) {
            AtomicInteger ai = new AtomicInteger(1);
            new Student(ai, 1, "A").start();
            new Student(ai, 2, "B").start();
            new Student(ai, 0, "C").start();
        }

    }

    class Student extends Thread {
        AtomicInteger ai;
        int b;
        String c;

        Student(AtomicInteger a, int b, String c) {
            this.ai = a;
            this.b = b;
            this.c = c;
        }

        public void run() {
            while (true) {
                synchronized (ai) {
                    int val = ai.intValue();
                    if (val >= 10) {
                        ai.notifyAll();
                        break;
                    } else {
                        if (val % 3 == b) {
                            System.out.println(" Thread " + b + " printing value " + c);
                            ai.getAndIncrement();
                            ai.notifyAll();
                        } else {
                            try {
                                ai.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

输出

 Thread 1 printing value A
 Thread 2 printing value B
 Thread 0 printing value C
 Thread 1 printing value A
 Thread 2 printing value B
 Thread 0 printing value C
 Thread 1 printing value A
 Thread 2 printing value B
 Thread 0 printing value C

答案 4 :(得分:0)

您还可以通过以下方式解决上述问题

public class BasePatternPrintExample {

    public static void main(String[] args) {
        Status lock = new Status(1);
        ThreadA t1 = new ThreadA("A", lock);
        ThreadB t2 = new ThreadB("B", lock);
        ThreadC t3 = new ThreadC("C", lock);
        t1.start();
        t2.start();
        t3.start();
    }

}

状态类

class Status{
    private int status;

    public Status(int status){
        this.status = status;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

}

线程A

class ThreadA extends Thread {
    private Status lock;

    public ThreadA(String name, Status obj) {
        super(name);
        this.lock = obj;
    }

    public void run() {
        while(true) {
                synchronized (lock) {
                    lock.notifyAll();
                    //System.out.println(lock.getStatus());
                    while(lock.getStatus() != 1){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.print("A");
                    lock.setStatus(2);

                }
            }
    }
}

线程B

class ThreadB extends Thread {
    private Status lock;

    public ThreadB(String name, Status obj) {
        super(name);
        this.lock = obj;
    }

    public void run() {
        while(true) {
                synchronized (lock) {
                    lock.notifyAll();
                    while(lock.getStatus() != 2){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B");
                    lock.setStatus(3);

                }
            }
    }
}

ThreadC

class ThreadC extends Thread {
    private Status lock;

    public ThreadC(String name, Status obj) {
        super(name);
        this.lock = obj;
    }

    public void run() {
        while(true) {
                synchronized (lock) {
                    lock.notifyAll();
                    while(lock.getStatus() != 3){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                    lock.setStatus(1);

                }
            }
    }
}