JAVA--多线程_实现 12A34B56C........

java多线程——线程通信   sychronized 同步代码块。 使用  wait() , notifyAll().方法实现  两个线程输出12A34B56C78D......的效果。1~52   A~Z .

wait() 使当前线程沉睡

notifyAll() 唤醒所有沉睡的线程

主要注意点 sychronized 同步代码块 需要确定wait(),notifyAll的对象。 

 

package test02;

public class Test {
	public static void main(String[] args) {
		Print p = new Print();
		new MyThread01(p).start(); //线程1
		
		new MyThread02(p).start(); //线程2

	}
}

class Print {             //用来确定输出
	public int i = 1;
	public char s = 'A';
	public boolean flag = true;
}

class MyThread01 extends Thread {        //输出数字
	private Print p;

	public MyThread01() {
	};

	public MyThread01(Print p) {
		this.p = p;
	}

	public void run() {
		synchronized (p) {
			while (p.i <= 52) {
				if (p.flag) {
					System.out.print(p.i++);
					if (p.i % 2 == 1) {
						p.flag = false;
						p.notifyAll();
					}

				} else {
					try {
						p.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		}
	}

}

class MyThread02 extends Thread {  //输出字母
	private Print p;

	public MyThread02() {
	};

	public MyThread02(Print p) {
		this.p = p;
	}

	public void run() {
		synchronized (p) {
			while (p.s <= 'Z') {
				if (!p.flag) {
					System.out.print(p.s++);
					p.flag = true;
					p.notifyAll();
				} else {
					try {
						p.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用`wait()`和`notify()`方法来实现线程的同步,具体代码实现如下: ``` public class PrintNumberAndLetter { private static final Object lock = new Object(); private static int count = 1; private static char letter = 'A'; public static void main(String[] args) { Thread thread1 = new Thread(() -> { synchronized (lock) { while (count <= 52) { System.out.print(count++); System.out.print(count++); lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lock.notify(); } }); Thread thread2 = new Thread(() -> { synchronized (lock) { while (letter <= 'Z') { System.out.print(letter++); lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lock.notify(); } }); thread1.start(); thread2.start(); } } ``` 在`Thread1`中,通过`synchronized`关键字锁住了共享对象`lock`。在循环中,先打印两个数字,然后通过`notify()`方法通知`Thread2`线程可以执行,自己则等待。当`Thread2`线程执行完毕后,通过`wait()`方法释放锁,`Thread1`线程重新获取锁并继续执行。 在`Thread2`中,同样通过`synchronized`关键字锁住共享对象`lock`。在循环中,每次打印一个字母,然后通过`notify()`方法通知`Thread1`线程可以执行,自己则等待。当`Thread1`线程执行完毕后,通过`wait()`方法释放锁,`Thread2`线程重新获取锁并继续执行。 通过这种方式,实现了两个线程的同步,按照题目要求依次打印数字和字母。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值