Skip to content

Instantly share code, notes, and snippets.

@paomian
Created August 31, 2015 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paomian/7a95ec2125b46869280a to your computer and use it in GitHub Desktop.
Save paomian/7a95ec2125b46869280a to your computer and use it in GitHub Desktop.
pv java
import java.lang.Exception;
import java.lang.Object;
import java.lang.Runnable;
import java.lang.System;
import java.lang.Thread;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;
class MyQueue {
private final LinkedList<Object> ll;
private final int capacity;
private final Semaphore empty;
private final Semaphore full;
private int len;
public MyQueue(int c) {
this.capacity = c;
this.ll = new LinkedList<Object>();
this.empty = new Semaphore(c,true);
this.full = new Semaphore(0,true);
}
public Object get() throws InterruptedException {
full.acquire();
len -= 1;
empty.release();
return ll.poll();
}
public void put(Object obj) throws InterruptedException {
empty.acquire();
len += 1;
ll.add(obj);
full.release();
}
public boolean tryPut(Object obj) throws Exception {
if (len == capacity) {
return false;
} else if (len > capacity) {
throw new Exception("卧槽,你这代码写的有问题啊!");
} else {
empty.release();
len += 1;
ll.add(obj);
full.release();
return true;
}
}
}
class Global {
public static MyQueue queue = new MyQueue(10);
}
class Read implements Runnable {
final String name;
public void run() {
while (true) {
try {
Thread.sleep(100);
Object obj = Global.queue.get();
int a = (int)obj;
System.out.println(name + " " + a);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Read(String name) {
this.name = name;
}
}
class Write implements Runnable {
private final String name;
private int counter;
public void run() {
while (true) {
try {
Thread.sleep(1000);
counter += 1;
counter = counter % 10;
Global.queue.put(counter);
System.out.println(name + " put queeu " + counter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Write(String name) {
this.counter = 0;
this.name = name;
}
}
public class pv {
public static void main(String argc[]) {
Thread w1 = new Thread(new Write("write thread"));
Thread r1 = new Thread(new Read("read thread"));
w1.start();
r1.start();
try {
w1.join();
r1.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment