java多线程如何互锁
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程如何互锁相关的知识,希望对你有一定的参考价值。
不知你想问什么:是希望互锁? 还是希望避免互锁?一般来讲,是不希望互锁。即避免互相等待对方已经拥有的锁资源。比如有两个线程t1和t2,同时有两个锁m1,m2;在某个时刻,t1已经拥有锁m1,而t2已经拥有锁m2,接下来t1试图获得锁m2,并处于等待状态,而t2试图去获得锁m1,也处于等待状态。这种状况就是互锁,或者也叫死锁。
要想避免互锁或者死锁,良好的设计和规范的编码是很必要的,比如设计期间就要制定一个统一的协议,即m1,m2锁所保护的资源划归一个域,那么凡是在同一个域进行操作的线程都必须遵循相同的步骤去访问和修改资源。比如对待m1,m2来讲,凡是访问他们的线程都遵循先获取m1然后再获取m2的规则,这样就可以有效避免互锁和死锁。 参考技术A 静态对象 参考技术B 代码说话:
package ini.hust.thread;
public class TestDeadLock
public static void main(String[] args)
SharedSource_A a = new SharedSource_A();
SharedSource_B b = new SharedSource_B();
Thread_A ta = new Thread_A(a, b);
Thread_B tb = new Thread_B(a, b);
ta.start();
tb.start();
class SharedSource_A
private boolean isUsing = false;
public boolean isUsing()
return isUsing;
public void setIsUsing(boolean isUsing)
this.isUsing = isUsing;
class SharedSource_B
private boolean isUsing = false;
public boolean isUsing()
return isUsing;
public void setIsUsing(boolean isUsing)
this.isUsing = isUsing;
class FatherThread extends Thread
public synchronized void useSharedSource_A(SharedSource_A a, SharedSource_B b)
a.setIsUsing(true);
try
sleep(5000);
catch(InterruptedException ie)
ie.printStackTrace();
while(b.isUsing())
;
a.setIsUsing(false);
public synchronized void useSharedSource_B(SharedSource_B b,SharedSource_A a)
b.setIsUsing(true);
try
sleep(2000);
catch(InterruptedException ie)
ie.printStackTrace();
while(a.isUsing())
;
b.setIsUsing(false);
class Thread_A extends FatherThread
private SharedSource_A a;
private SharedSource_B b;
public Thread_A(SharedSource_A a, SharedSource_B b)
this.a = a;
this.b = b;
public void run()
useSharedSource_A(a, b);
useSharedSource_B(b, a);
class Thread_B extends FatherThread
private SharedSource_A a;
private SharedSource_B b;
public Thread_B(SharedSource_A a, SharedSource_B b)
this.a = a;
this.b = b;
public void run()
useSharedSource_B(b, a);
useSharedSource_A(a, b);
(C语言)为啥我这样调用线程里的结构体参数会报错
struct test
long b[NUM];
long lleft;
long rright;
;
unsigned __stdcall FirstThreadFunc(void*arg)
int left=first->lleft;
int right=first->rright;
fun(b,left,right);
int main()
a数组之前已经设好
unsigned threadID[4];
struct text first;
first.b=a;
first.lleft=0;
first.rright=c1-1;
hThread[0]=(HANDLE)_beginthreadex(NULL,0,FirstThreadFunc,(void*)&first,0,&threadID[0]);
很多东西我省略了,就是不明白为什么会一直提示我
error C2065: 'first' : undeclared identifier
left of '->lleft' must point to class/struct/union
left of '->rright' must point to class/struct/union
诸如此类很多。。。
到底该改哪里?各位老师麻烦指导下,谢谢!!
所以括号里面到底怎么填写?
追答加上这一行struct text*first = (struct text*)arg;
int left=first->lleft;
还有,text和test不一样,把它们弄成一样
以上是关于java多线程如何互锁的主要内容,如果未能解决你的问题,请参考以下文章