导航

三个线程,ABC 10次(volatile+synchronized)

Posted on 2018-08-27 01:02  骄阳照林  阅读(278)  评论(0编辑  收藏  举报
package ThreadABC;

public class Share {
private volatile int status;

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public Share(int status) {
this.status = status;
}
}

package ThreadABC;

public class A implements Runnable {
private int num =0;
private Share lock;
@Override
public void run() {
for(;num < 10;){
if(lock.getStatus()%3==1) {
System.out.print("A");
synchronized(lock) {
lock.setStatus(lock.getStatus()+1);
}
num++;
}
}
}

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public A(Share lock) {
this.lock = lock;
}
}

package ThreadABC;

public class B implements Runnable {
private int num =0;
private Share lock;
@Override
public void run() {
for(;num < 10;){
if(lock.getStatus()%3==2) {
System.out.print("B");
synchronized(lock) {
lock.setStatus(lock.getStatus()+1);
}
num++;
}
}
}

public B(Share lock) {
this.lock = lock;
}
}

package ThreadABC;

public class C implements Runnable {
private int num =0;
private Share lock;
@Override
public void run() {
for(;num < 10;){
if(lock.getStatus()%3==0) {
System.out.println("C");
synchronized(lock) {
lock.setStatus(lock.getStatus()+1);
}
num++;
}
}
}

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public C(Share lock) {
this.lock = lock;
}
}

package ThreadABC;

public class Test {
public static void main(String[] args){
Share o = new Share(1);
A a = new A(o);
B b = new B(o);
C c = new C(o);
Thread a1 = new Thread(a);
Thread b1 = new Thread(b);
Thread c1 = new Thread(c);
a1.start();
b1.start();
c1.start();
}
}