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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

java两个线程循环打印_java循环打印 多线程

發布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java两个线程循环打印_java循环打印 多线程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述

Java多線程,循環打印”我是多線程”10次。

思路:

1 開啟5個線程 "我" "是" "多" "線" "程",控制鎖的等待 釋放順序

2 for循環10次

/**

* @Method

* @Author 孤獨的main()函數

* @Version 1.0

* @Description

* @Return

* @Exception

* @Date 2019/2/11 10:56

*/

public class print {

private static int state = 0;

public static void main(String[] args) {

final print t = new print();

Thread A = new Thread(new Runnable() {

public synchronized void run() {

// 設定打印10次

for (int i = 0; i < 10; i++) {

synchronized (t) {

// 如果不滿足打印條件,則調用wait,一直阻塞

while (state % 5 != 0) {

try {

t.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

// 執行到這里,表明滿足條件,打印,設置state

// 調用notifyAll方法

System.out.print("我");

state++;

t.notifyAll();

}

}

}

});

Thread B = new Thread(new Runnable() {

public synchronized void run() {

for (int i = 0; i < 10; i++) {

synchronized (t) {

while (state % 5 != 1) {

try {

t.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.print("是");

state++;

t.notifyAll();

}

}

}

});

Thread C = new Thread(new Runnable() {

public synchronized void run() {

for (int i = 0; i < 10; i++) {

synchronized (t) {

while (state % 5 != 2) {

try {

t.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.print("多");

state++;

t.notifyAll();

}

}

}

});

Thread D = new Thread(new Runnable() {

public synchronized void run() {

for (int i = 0; i < 10; i++) {

synchronized (t) {

while (state % 5 != 3) {

try {

t.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.print("線");

state++;

t.notifyAll();

}

}

}

});

Thread E = new Thread(new Runnable() {

public synchronized void run() {

for (int i = 0; i < 10; i++) {

synchronized (t) {

while (state % 5 != 4) {

try {

t.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.print("程");

System.out.println();

state++;

System.out.println(state);

t.notifyAll();

}

}

}

});

A.start();

B.start();

C.start();

D.start();

E.start();

}

}

總結

以上是生活随笔為你收集整理的java两个线程循环打印_java循环打印 多线程的全部內容,希望文章能夠幫你解決所遇到的問題。

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