2018年7月19日木曜日

java_Semaphore

java_Semaphore

import java.util.concurrent.Semaphore;
import java.lang.System;

class  M180717_Semaphore {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(8);
long s = System.currentTimeMillis();

A a = new A(semaphore);
a.start();

B b = new B(semaphore);
b.start();

B b2 = new B(semaphore);
b2.start();
}
}

class A extends Thread {
private Semaphore semaphore;
public A(Semaphore semaphore) {
this.semaphore = semaphore;
}

@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("a");
}
semaphore.release();
} catch (Exception e) {
System.out.println(semaphore.getQueueLength());
}
}
}

class B extends Thread {
private Semaphore semaphore;

public B(Semaphore semaphore) {
this.semaphore = semaphore;
}

@Override
public void run() {
try {
// System.out.println(semaphore.getQueueLength());
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("b");
}
semaphore.release();
} catch (Exception e) {
System.out.println(semaphore.getQueueLength());
}
}
}

class C extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("c");
}
}
}

class X implements Runnable {
@Override
public void run() {
System.out.println("xxxxx");
}
}


0 件のコメント: