`

多线程交替打印

阅读更多
public class NThread implements Runnable {
	static Object o=new Object();
	volatile static int index=0;
	static int n=10;  //线程数量
	int max=100;   //打印次数
	int i;        //线程名
	public NThread(int i) {
		this.i=i;
	}
	public static void main(String[] args) {
		for(int j=0;j<n;j++) {
			(new Thread(new NThread(j))).start();
		}

	}

	public void run() {
		while(true) {
			synchronized (o) { //不加这个会卡死报异常
				if(index>=max) {
					o.notify();//加上这个可以结束
					break;
				}
				if(index%n!=i) {
					try {
						o.wait();
					} catch (InterruptedException e) {					
						e.printStackTrace();
					}
				}else {
					System.out.println(i+"-->"+index);
					index++;
					o.notifyAll();//只能用notifyAll,用notify会只执行一次卡死
					try {
						o.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
	}

}

 

0-->0
1-->1
2-->2
3-->3
4-->4
5-->5
6-->6
7-->7
8-->8
9-->9
0-->10


0-->90
1-->91
2-->92
3-->93
4-->94
5-->95
6-->96
7-->97
8-->98
9-->99

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics