题目如下:
四个线程1,2,3,4. 线程1,2对变量i加一. 线程3,4对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0 1 2 1 0 1 2 1 0 1 2...
class="java">package test01;
import java.util.concurrent.LinkedBlockingQueue;
public class ThreadUtil {
private LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(
4);
private int count = 0;
@SuppressWarnings("boxing")
public ThreadUtil() {
lbq.offer(1);
lbq.offer(2);
lbq.offer(3);
lbq.offer(4);
}
@SuppressWarnings("boxing")
public synchronized void inc(int content) {
while (true) {
int temp = lbq.peek();
if (temp == content) {
break;
}
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(count + " ");
count++;
try {
lbq.offer(lbq.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
//print();
}
@SuppressWarnings("boxing")
public synchronized void dec(int content){
while (true) {
int temp = lbq.peek();
if (temp == content) {
break;
}
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(count + " ");
count--;
try {
lbq.offer(lbq.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
//print();
}
private void print()
{
System.out.println("=====>"+lbq.toString());
}
}
package test01;
public class IncThread implements Runnable {
private ThreadUtil tu;
private int content;
public IncThread(ThreadUtil tu, int content) {
this.tu = tu;
this.content = content;
}
@Override
public void run() {
while (true) {
tu.inc(content);
}
}
}
package test01;
public class DecThread implements Runnable{
private ThreadUtil tu;
private int content;
public DecThread(ThreadUtil tu,int content) {
this.tu = tu;
this.content = content;
}
@Override
public void run() {
while (true) {
tu.dec(content);
}
}
}
package test01;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test01 {
public static void main(String[] args) {
ThreadUtil tu = new ThreadUtil();
ExecutorService exec = Executors.newFixedThreadPool(4);
exec.submit(new IncThread(tu, 1));
exec.submit(new IncThread(tu, 2));
exec.submit(new DecThread(tu, 3));
exec.submit(new DecThread(tu, 4));
exec.shutdown();
}
}
运行结果如下:
0 1 2 1 0 1 2 1 0 1 2 1 0 1 2 1
参考自:http://ethanzhou.blog.51cto.com/6147883/1045683