三個執行緒迴圈列印123-多執行緒

享受旅行中的VIP快樂發表於2020-10-15
public class ThreadTest {

    static int a = 0;

    public ThreadTest(int a){
        this.a = a;
    }

	//執行緒1呼叫的方法
    public synchronized void printOne(){
            try {
                while (a%3!=1){
                    this.wait();
                }
              System.out.println(Thread.currentThread().getName()+"---" + a++);
                Thread.sleep(1000);
                this.notifyAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

    }

	//執行緒2呼叫的方法
    public synchronized void printTwo(){
        try {
            while (a%3!=2){
                this.wait();
            }
            System.out.println(Thread.currentThread().getName()+"---" + a++);
            Thread.sleep(1000);
            this.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
	
	//執行緒3呼叫的方法
    public synchronized void printThree(){
        try {
            while (a%3!=0){
                this.wait();
            }
            System.out.println(Thread.currentThread().getName()+"---" + a++);
            Thread.sleep(100);
            this.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    //主方法
    public static void main(String[] args) {

        ThreadTest a = new ThreadTest(0);

        Thread threadOne = new Thread(new PrintOne(a));
        Thread threadTwo = new Thread(new PrintTwo(a));
        Thread threadThree = new Thread(new PrintThree(a));

        threadOne.setName("one");
        threadTwo.setName("two");
        threadThree.setName("three");

        threadOne.start();
        threadTwo.start();
        threadThree.start();


    }



}



//執行緒1
class PrintOne implements Runnable{
    private ThreadTest threadTest;

    public PrintOne(ThreadTest threadTest){
        this.threadTest = threadTest;
    }

    @Override
    public void run() {
        while (true){
            threadTest.printOne();
        }
    }
}

class PrintTwo implements Runnable{
    private ThreadTest threadTest;

    public PrintTwo(ThreadTest threadTest){
        this.threadTest = threadTest;
    }

    @Override
    public void run() {
        while (true){
            threadTest.printTwo();
        }
    }
}


class PrintThree implements Runnable{
    private ThreadTest threadTest;

    public PrintThree(ThreadTest threadTest){
        this.threadTest = threadTest;
    }

    @Override
    public void run() {
        while (true){
            threadTest.printThree();
        }
    }
}

相關文章