Java两个线程交替打印输出a1b2c3d4

1、线程1负责输出abcd

public class Thread1 extends Thread {
	//定义锁对象,负责接收传入对象
	private final Object lock;
	//定义共有构造方法
	public Thread1(Object lock) {
		// TODO Auto-generated constructor stub
		this.lock = lock;
	}
	
	@Override
	public void run() {
		String[] string = {"a", "b", "c", "d"};
		for (int i = 0; i < string.length; i++) {
			synchronized (lock) {
				//线程1开始执行
				lock.notify();
				try {
					//线程1开始等待
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//线程1继续执行
				System.out.print(string[i]);
				//线程1运行结束
				lock.notify();
			}
		}
	}
}

2、线程2负责输出1234

public class Thread2 extends Thread {
	//定义锁对象,负责接收传入对象
	private final Object lock;
	//定义共有构造方法
	public Thread1(Object lock) {
		// TODO Auto-generated constructor stub
		this.lock = lock;
	}
	
	@Override
	public void run() {
		String[] string = {"1", "2", "3", "4"};
		for (int i = 0; i < string.length; i++) {
			synchronized (lock) {
				//线程2开始执行
				lock.notify();
				try {
					//线程2开始等待
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//线程2继续执行
				System.out.print(string[i]);
				//线程2运行结束
				lock.notify();
			}
		}
	}
}

3、创建测试类

public class Test {
	public static void main(String[] args){
		// TODO Auto-generated method stub
		final Object lock = new Object();
		Thread1 t1 = new Thread1(lock);
		Thread2 t2 = new Thread2(lock);
		t1.start();
		t2.start();
	}
}

输出结果

a1b2c3d4

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值