java 多线程交替顺序打印1234。。。

  • Post author:
  • Post category:java


package com.dert;

public class ChangeThreadTest {

int num = 1;
int max = 4;
final Object lock = new Object();

class ChangeThread extends Thread {
	
	private int index;
	public void setLock(int index) {
		this.index = index;
		this.setName(""+index);
	}

	public void run() {
		while (num < 100) {
			synchronized (lock) {
				lock.notify();// 唤醒lock上的其他的线程,其他的线程是随机的
				if (num % max == index) {
					System.out.println(this.getName() + "num = " + num++);
				}
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

public void startJob() {
	for (int i = 0; i < max; i++) {
		ChangeThread changeThread = new ChangeThread();
		changeThread.setLock(i);
		changeThread.start();
	}
}

public static void main(String[] args) {	
	ChangeThreadTest changeThreadTest = new ChangeThreadTest();
	changeThreadTest.startJob();
}

}

直接上代码 max 表示要多少个线程顺序打印数据。随便你设置



版权声明:本文为kkk0526原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。