java 多线程顺序打印_[java]多线程顺序打印

package com.dongshuo.test.multithread;

import javafx.beans.binding.ObjectExpression;

/**

* @author :dongshuo

* @date : 2018/11/18 18:33

* @desc : 3个线程交替打印

*/

public class 多线程交替打印 {

public static class ThreadPriter implements Runnable {

private String name; //名字

private Object pre; //前一把锁

private Object self; //当前锁

public ThreadPriter(String name, Object pre, Object self) {

this.name = name;

this.pre = pre;

this.self = self;

}

@Override

public void run() {

//打印10次

int count = 10;

while (count > 0) {

synchronized (pre) {

synchronized (self) {

//打印

System.out.print(name);

count--;

//唤醒其他线程

self.notifyAll();

}

//释放 pre锁

try {

if (count == 0) {

pre.notifyAll();

} else {

pre.wait();

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

public static void main(String[] args)throws Exception{

Object a = new Object();

Object b = new Object();

Object c = new Object();

ThreadPriter A = new ThreadPriter("A",c,a);

ThreadPriter B = new ThreadPriter("B",a,b);

ThreadPriter C = new ThreadPriter("C",b,c);

new Thread(A).start();

Thread.sleep(10);

new Thread(B).start();

Thread.sleep(10);

new Thread(C).start();

Thread.sleep(10);

}

}

package com.dongshuo.test.multithread;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

/**

* @author :dongshuo

* @date : 2018/11/18 19:01

* @desc :

*/

public class 可重入锁 {

private static Lock lock = new ReentrantLock();

private static int state = 0;

public static class ThreadA extends Thread {

@Override

public void run() {

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

try {

lock.lock();

while (state % 3 == 0) {

System.out.print("A");

state++;

i++;

}

} finally {

lock.unlock();

}

}

}

}

public static class ThreadB extends Thread {

@Override

public void run() {

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

try {

lock.lock();

while (state % 3 == 1) {

System.out.print("B");

state++;

i++;

}

} finally {

lock.unlock();

}

}

}

}

public static class ThreadC extends Thread {

@Override

public void run() {

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

try {

lock.lock();

while (state % 3 == 2) {

System.out.print("C");

state++;

i++;

}

} finally {

lock.unlock();

}

}

}

}

public static void main(String[] args) throws Exception {

new ThreadA().start();

new ThreadB().start();

new ThreadC().start();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值