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循环打印 多线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java编写胖老鼠的交易_猫和胖老鼠
- 下一篇: java2018笔试基础题_java基础