欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java,

来源: javaer 分享于  点击 38505 次 点评:76

java,


看到一个简单线程面试题,尝试着做一下。

已经好久没碰过线程知识了,顺便看有没有忘记 

 

package thread.plus_sub;

/**
 * 题目如下:
 * 
 * 四个线程a,b,c,d. 线程a,b对变量i加一. 线程c,d对变量i减去一. 
 * 四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0
 * 1 2 1 0 1 2 1 0 1 2...
 * 
 * @author loveiceberg
 * 
 */
public class Print012 {

	// 按照顺序循环生成编号 0,1,2,3,0,1,2,3......
	static class IndexGenerator {
		int index = 0;

		int getValue() {
			return index;
		}

		void next() {
			index = (index + 1) % 4;
		}
	}

	static class Plus_Sub implements Runnable {
		// 需要打印输出的值
		static int value = 0;
		// 当前线程的ID(不是真是ID,用来判断执行顺序)
		int id;
		// 加,减号标识
		String flag;
		// 序号循环生成器
		IndexGenerator generator;

		public Plus_Sub(int id, String flag, IndexGenerator geneartor) {
			this.id = id;
			this.flag = flag;
			this.generator = geneartor;
		}

		@Override
		public void run() {
			synchronized (Plus_Sub.class) {
				while (generator.getValue() != id) {
					try {
						Plus_Sub.class.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				if (flag.equals("+")) {
					value++;
				} else {
					value--;
				}
				System.out.println(value);
				Plus_Sub.class.notifyAll();
				generator.next();
			}
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		IndexGenerator generator = new IndexGenerator();
		Thread t1 = new Thread(new Plus_Sub(0, "+", generator));
		Thread t2 = new Thread(new Plus_Sub(1, "+", generator));
		Thread t3 = new Thread(new Plus_Sub(2, "-", generator));
		Thread t4 = new Thread(new Plus_Sub(3, "-", generator));

		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

 

相关文章

    暂无相关文章
相关栏目:

用户点评