java 多线程实例之打印字母数字

本文通过一个Java示例程序介绍了如何使用synchronized关键字实现线程间的同步机制,确保两个线程交替打印数字和字母,以此来解决多线程环境下的数据一致性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ThreadTest {
	public static void main(String[] args) {
		Print p = new Print();
		
		Num n = new Num(p);
		A a = new A(p);
		
		Thread t1 = new Thread(n);
		Thread t2 = new Thread(a);
		
		t1.start();
		t2.start();
	}
}



//打印
class Print{
	boolean flag = false;
	//synchronized  修饰方法/代码块 会调用锁保护方法/代码块
	public synchronized void printnum() throws InterruptedException {
		for(int i=1;i<=52;i++) {
			while(flag) {
				this.wait();
			}
			System.out.print(i);
			if(i%2==0) {
				flag = true;
				this.notifyAll();
			}
		}
	}
//synchronized  修饰方法/代码块 会调用锁保护方法/代码块  flag 被保护
	public synchronized void printa() throws InterruptedException {
		for(int i=1;i<=26;i++) {
			while(!flag) {
				this.wait();
			}
			System.out.print((char)(i+64));
			flag = false;
			this.notifyAll();
		}
	}
}



//数字
class Num implements Runnable{
	Print p;
	public Num(Print p) {
		super();
		this.p = p;
	}
	public void run() {
		try {
			p.printnum();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

//字母
class A implements Runnable{
	Print p;
	public A(Print p) {
		super();
		this.p = p;
	}
	public void run() {
		try {
			p.printa();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
当多个线程对同一个资源进行访问和操作的时候就会出现数据一致性问题。一致性问题得不到解决多个任务的操作永远得不到正确的结果,解决一致性问题的方法就是同步机制。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值