日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java实现123n_java三线程交替打印123……n

發布時間:2023/12/2 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java实现123n_java三线程交替打印123……n 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用多線程交替打印1--n,a進程打印1,4,7,……(3n+1),b進程打印2,7,10,……(3n+2),c進程打印3,6,9,……(3n)

涉及到多線程的同步,阻塞,wait,notify

代碼如下

Num.java

public class Num {

private int num = 0;

public Num(int num) {

this.num = num;

}

public synchronized void printOne() {

try {

while (num%3!=1) {

this.wait();

}

System.out.println(Thread.currentThread().getName() + "------->"

+ (num++));

Thread.sleep(1000);

this.notifyAll();

} catch (Exception e) {

e.printStackTrace();

}

}

public synchronized void printTwo() {

try {

while (num%3!=2) {

this.wait();

}

System.out.println(Thread.currentThread().getName() + "------->"

+ (num++));

Thread.sleep(1000);

this.notifyAll();

} catch (Exception e) {

e.printStackTrace();

}

}

public synchronized void printThr() {

try {

while (num%3!=0) {

this.wait();

}

System.out.println(Thread.currentThread().getName() + "------->"

+ (num++));

Thread.sleep(1000);

this.notifyAll();

} catch (Exception e) {

e.printStackTrace();

}

}

} 三個線程類

public class PrintOne implements Runnable {

private Num num;

public PrintOne(Num num) {

this.num = num;

}

@Override

public void run() {

while (true) {

num.printOne();

}

}

}

public class PrintTwo implements Runnable {

private Num num;

public PrintTwo(Num num) {

this.num = num;

}

@Override

public void run() {

while (true) {

num.printTwo();

}

}

}

public class PrintThr implements Runnable {

private Num num;

public PrintThr(Num num) {

this.num = num;

}

@Override

public void run() {

while (true) {

num.printThr();

}

}

}

測試類

public class Test {

public static void main(String[] args) {

Num num = new Num(0);

Thread pOne = new Thread(new PrintOne(num));

Thread pTwo = new Thread(new PrintTwo(num));

Thread pThr = new Thread(new PrintThr(num));

pOne.setName("3n+1");

pTwo.setName("3n+2");

pThr.setName("3n ");

pOne.start();

pTwo.start();

pThr.start();

}

}

效果

3n ------->0

3n+1------->1

3n+2------->2

3n ------->3

3n+1------->4

3n+2------->5

…………

總結

以上是生活随笔為你收集整理的java实现123n_java三线程交替打印123……n的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。