问题描述
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();
}
}