【多线程题库】两个线程轮流打印

问题描述:

  • 使用两个线程A、B轮流打印出1-100,例如:A:1,B:2,A:3,B:4…

资源类

public class Printf {
	public int i = 0;
}

线程类

public class MyThread extends Thread{
	private  Printf obj;
	public MyThread(Printf obj) {
		this.obj = obj;
	}
	
	@Override
	public void run() {
		synchronized (obj) {
			while(obj.i < 100) {
				if(currentThread().getName().equals("A")) {
					System.out.println("A:"+ ++obj.i);
					try {
						obj.notify();
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}else {
					System.out.println("B:"+ ++obj.i);
					try {
						obj.notify();
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			obj.notify();
		}
	}
}

主方法类

public class TestMain {
	public static int i = 0;
	public static void main(String[] args) {
		Printf p = new Printf();
		MyThread a = new MyThread(p);
		MyThread b = new MyThread(p);
		a.setName("A");
		b.setName("B");
		a.start();
		b.start();
	}
}

执行结果

【多线程题库】两个线程轮流打印_第1张图片

你可能感兴趣的:(【多线程题库】)