多线程上机题

[b]题目如下:
四个线程1,2,3,4. 线程1,2对变量i加一. 线程3,4对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0 1 2 1 0 1 2 1 0 1 2...[/b]
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值