Java多线程题目,Java多线程
分享于 点击 38720 次 点评:20
Java多线程题目,Java多线程
本文转载自ethanzhou的51CTO博客
题目如下:
四个线程a,b,c,d. 线程a,b对变量i加一. 线程c,d对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0 1 2 1 0 1 2 1 0 1 2…
package demo;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
* 四个线程a,b,c,d. 线程a,b对变量i加一.
* 线程c,d对变量i减去一.四个线程顺序执行,
* 每个线程每次只执行一次.i的初始值为0,
* 打印结果0 1 2 1 0 1 2 1 0 1 2...
*
*/
public class Demo02 {
private int i = 0;
private BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
public Demo02() {
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
}
public synchronized void plus(int condition) throws InterruptedException{
while(true){
int c = queue.peek();
if (c==condition) {
break;
}else {
notifyAll();
wait();
}
}
queue.offer(queue.take());
i++;
System.out.println(Thread.currentThread().getName()+",i="+i);
}
public synchronized void subtract(int condition) throws InterruptedException{
while(true){
int c = queue.peek();
if (c==condition) {
break;
}else {
notifyAll();
wait();
}
}
queue.offer(queue.take());
i--;
System.out.println(Thread.currentThread().getName()+",i="+i);
}
private class plusThread implements Runnable{
// 条件
private int condition;
public plusThread(int condition) {
this.condition = condition;
}
@Override
public void run() {
while (true){
try {
plus(condition);
} catch (InterruptedException e) {
System.err.println(Thread.currentThread().getName() + " exit now");
break;
}
}
}
}
private class subtractThread implements Runnable{
private int condition;
public subtractThread(int condition) {
this.condition = condition;
}
@Override
public void run() {
while (true){
try {
subtract(condition);
} catch (InterruptedException e) {
System.err.println(Thread.currentThread().getName() + " exit now");
break;
}
}
}
}
public static void main(String[] args) {
Demo02 demo02 = new Demo02();
ExecutorService exec = Executors.newFixedThreadPool(4);
exec.submit(demo02. new plusThread(1));
exec.submit(demo02.new plusThread(2));
exec.submit(demo02. new subtractThread(3));
exec.submit(demo02.new subtractThread(4));
exec.shutdown();
}
}
这段代码顺便让我温顾了线程池,BlockingQueue类的一些方法,对于链式的LinkedBlockingQueue也有了更形象的认识,固转载记录一下。
相关文章
- 暂无相关文章
用户点评