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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值