多线程笔记—实现互斥效果

实现多线程的互斥效果

          第一种是通过sychronized与wait,notify,具体代码如下

public class TestThread {	
public static  boolean isF=false;
public static void main(String[] args) {	
	final Arth arth = new Arth();
		new Thread(new Runnable(){
			@Override
			public void run() {
				for(int i=0;i<10;i++){
						arth.test1();
				}
			}
		}).start();
		new Thread(new Runnable(){
			@Override
			public void run() {
				for(int i=0;i<10;i++){
					arth.test2();
				}
			}
		}).start();		
}
static class Arth{
	public synchronized void test1(){
		while(isF){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
			for(int i=1;i<11;i++){
				System.out.println("A "+Thread.currentThread().getName()+"   "+i);
			}
		isF=true;
		this.notify();
	}
	public synchronized void test2(){
		while(!isF){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
			for(int i=1;i<21;i++){
				System.out.println("B "+Thread.currentThread().getName()+i);
		}
		isF=false;
		this.notify();
	}
}
}
运行结果

A Thread-0   1
A Thread-0   2
A Thread-0   3
A Thread-0   4
A Thread-0   5
A Thread-0   6
A Thread-0   7
A Thread-0   8
A Thread-0   9
A Thread-0   10
B Thread-11
B Thread-12
B Thread-13
B Thread-14
B Thread-15
B Thread-16
B Thread-17
B Thread-18
B Thread-19
B Thread-110
B Thread-111
B Thread-112
B Thread-113
B Thread-114
B Thread-115
B Thread-116
B Thread-117
B Thread-118
B Thread-119
B Thread-120
A Thread-0   1
A Thread-0   2
A Thread-0   3
A Thread-0   4
A Thread-0   5
A Thread-0   6
A Thread-0   7
A Thread-0   8
A Thread-0   9
A Thread-0   10
B Thread-11
B Thread-12 

     第二种是通过Condition与ReentrantLock来实现,具体如下:

public class ThreadA2 extends Thread{
	private MyService2 service;
	public ThreadA2(MyService2 service) {
		super();
		this.service = service;
	}
	@Override
	public void run() {
		super.run();
		for(int i=0;i<Integer.MAX_VALUE;i++){
			service.set();
		}
	}
}
public class ThreadB2 extends Thread{
	private MyService2 service;
	public ThreadB2(MyService2 service) {
		super();
		this.service = service;
	}
	@Override
	public void run() {
		super.run();
		for(int i=0;i<Integer.MAX_VALUE;i++){
			service.get();
		}
	}
}
public class MyService2 {
private ReentrantLock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
private boolean hasValue=false;
public void set(){
	try {
		lock.lock();
		while(hasValue==true){
			condition.await();
		}
		System.out.println("打印 11");
		hasValue=true;
		condition.signal();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		lock.unlock();
	}
}
  public void get(){
	  try {
		lock.lock();
		while(hasValue==false){
			condition.await();
		}
		System.out.println("复印 22");
		hasValue=false;
		condition.signal();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		lock.unlock();
	}
  }
}
public class Run {
	public static void main(String[] args) {
		MyService2 myService2 = new MyService2();
		ThreadA2 threadA = new ThreadA2(myService2);
		threadA.start();
		ThreadB2 myThreadB2 = new ThreadB2(myService2);
		myThreadB2.start();
	}
}
运行结果:

打印 11
复印 22
打印 11
复印 22
打印 11
复印 22
打印 11
复印 22
打印 11
复印 22
打印 11
复印 22


synchronize与ReentrantLock的区别:

      1.lock 必须在 finally 块中释放。否则,如果受保护的代码将抛出异常,锁就有可能永远得不到释放。

     2 对于synchronized来讲,被synchronized锁定的资源(代码块),线程A,只有执行完毕,才能释放锁,对于长时间的同步块来讲,其他线程线程B在很长时间内都得不到执行,如果B想中断自己,在synchronized锁定下,这种情况B不会中断。ReentranceLock之所以可以重入,是因为线程在执行的过程可以中断,对于某些等待时间较长的同步块,可以中断,而转去执行其他的操作。

      3 ReentranceLock可以同时绑定多个Condition,synchronized只能绑定一个Condition,也就是锁定的对象。










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C#中,可以使用多个互斥锁来实现多线程的同步。互斥锁是一种同步机制,用于保护共享资源,一次只允许一个线程访问被锁定的代码块。下面是使用多个互斥锁的示例代码: ```csharp using System; using System.Threading; class Program { static Mutex mutex1 = new Mutex(); static Mutex mutex2 = new Mutex(); static void Main() { // 创建两个线程 Thread thread1 = new Thread(DoWork1); Thread thread2 = new Thread(DoWork2); // 启动线程 thread1.Start(); thread2.Start(); // 等待两个线程执行完毕 thread1.Join(); thread2.Join(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } static void DoWork1() { Console.WriteLine("Thread 1 is waiting for mutex1..."); mutex1.WaitOne(); Console.WriteLine("Thread 1 acquired mutex1. Doing some work..."); // 模拟耗时操作 Thread.Sleep(2000); Console.WriteLine("Thread 1 is waiting for mutex2..."); mutex2.WaitOne(); Console.WriteLine("Thread 1 acquired mutex2. Continuing work..."); // 执行一些其他操作 // 释放互斥锁 mutex2.ReleaseMutex(); mutex1.ReleaseMutex(); } static void DoWork2() { Console.WriteLine("Thread 2 is waiting for mutex2..."); mutex2.WaitOne(); Console.WriteLine("Thread 2 acquired mutex2. Doing some work..."); // 模拟耗时操作 Thread.Sleep(2000); Console.WriteLine("Thread 2 is waiting for mutex1..."); mutex1.WaitOne(); Console.WriteLine("Thread 2 acquired mutex1. Continuing work..."); // 执行一些其他操作 // 释放互斥锁 mutex1.ReleaseMutex(); mutex2.ReleaseMutex(); } } ``` 在上面的示例中,我们创建了两个互斥锁 `mutex1` 和 `mutex2`,并且分别在 `DoWork1` 和 `DoWork2` 方法中使用了这两个互斥锁来保护共享资源。注意,在获取互斥锁之后,需要在适当的时候释放互斥锁,以便其他线程可以获取它们。 请注意,使用多个互斥锁可能会导致死锁问题,因此在设计多线程应用程序时需要小心处理锁的使用顺序和释放顺序,以避免死锁情况的发生。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值