您的位置:首页 > 其它

四个线程a,b,c,d. 线程a,b对变量i加一. 线程c,d对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0 1 2 1 0 1 2 1 0 1 2...

2010-06-15 11:04 381 查看
代码如下:

package com.thread.test;

public class Testabc implements Runnable {
//确定哪个线程在工作
private static int count = 0;
//线程标志
private int id;
//线程工作次数
private int pCount;
//当前工作线程标志
int current;
//要输出的i
static int i = 0;

public Testabc(int id) {
this.id = id;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread a = new Thread(new Testabc(0),"a");
Thread b = new Thread(new Testabc(1),"b");
Thread c = new Thread(new Testabc(2),"c");
Thread d = new Thread(new Testabc(3),"d");
a.start();
b.start();
c.start();
d.start();
}

public void run() {
// TODO Auto-generated method stub
synchronized("lock"){
for(;;){
current = count%4;
if(current == id){
if(current == 0 || current == 1){
//给i自增
System.out.print(i+" ");
i++;
}else{
System.out.print(i+" ");
i--;
//i自减
}
count++;
pCount++;
"lock".notifyAll();
if(pCount == 10)break;
}else{
try{
"lock".wait();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐