.net 多线程 lock锁的问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net 多线程 lock锁的问题相关的知识,希望对你有一定的参考价值。

一个一直让我不明白的地方

statie int i=1;

void s()

lock(this)

i+=1;

response.wirte(i.ToString());


上面是我手写的一点代码 其实意思很简单 就是我现在有一个静态变量i
用10个线程来执行一个方法 每执行完这个方法 就要给i加1 当i到了1000的时候 就自动 把10个线程停止
可是我这样写 i总是有重复 或者 有的没有 我觉得应该是 lock那里的问题 是不是我写错了?为什么总锁不住i?
说简单一点吧
Thread[] td = new Thread[5];
for (int i = 0; i < td.Length; i++)

td[i] = new Thread(new ThreadStart(AgentIPjc));
td[i].Start();


public static void AgentIPjc()

while (true)

string[] _url = null;
lock (s)

if (_i >= _strs.Length)

Thread.CurrentThread.Abort();
// break;

_url = _strs[_i].Split(':');
_i += 1;

if (Helper.Request_Source_Proxy(_url[0], _url[1]))

if (_sb.Length > 0)

_sb.Append("|");

_sb.Append(_url[0] + ":" + _url[1]);




在AgentIPjc方法里的局部变量url

第二个线程 会不会修改第一个线程中的url

可能你在10个线程里创建了10个对象吧?
因为lock (this) 所以就会有10个锁变量,结果和不加锁的效果相同。
可以考虑static object slock = new object () ;
lock (slock)

因为对static变量访问,定义static锁变量比较贴切。
参考技术A 写法应该是没问题的

不过,建议在 WINFORM 或 console 程序中测试, ASP.NET 中不宜测试多线程
参考技术B static object i;

lock(i)

i = (int)i + 1;
参考技术C 我去死。本回答被提问者采纳 参考技术D 帮你解决了

多线程中的锁的几种用法总结

一、ReentrantLock

 1 package com.ietree.basicskill.mutilthread.lock;
 2 
 3 import java.util.concurrent.locks.Lock;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 /**
 7  * Created by Administrator on 2017/5/17.
 8  */
 9 public class UseReentrantLock {
10 
11     private Lock lock = new ReentrantLock();
12 
13     public void method1(){
14         try {
15             lock.lock();
16             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1..");
17             Thread.sleep(1000);
18             System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1..");
19             Thread.sleep(1000);
20         } catch (InterruptedException e) {
21             e.printStackTrace();
22         } finally {
23 
24             lock.unlock();
25         }
26     }
27 
28     public void method2(){
29         try {
30             lock.lock();
31             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method2..");
32             Thread.sleep(2000);
33             System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method2..");
34             Thread.sleep(1000);
35         } catch (InterruptedException e) {
36             e.printStackTrace();
37         } finally {
38 
39             lock.unlock();
40         }
41     }
42 
43     public static void main(String[] args) {
44 
45         final UseReentrantLock ur = new UseReentrantLock();
46         Thread t1 = new Thread(new Runnable() {
47             @Override
48             public void run() {
49                 ur.method1();
50                 ur.method2();
51             }
52         }, "t1");
53 
54         t1.start();
55         try {
56             Thread.sleep(10);
57         } catch (InterruptedException e) {
58             e.printStackTrace();
59         }
60         //System.out.println(ur.lock.getQueueLength());
61     }
62 
63 }

二、ReentrantReadWriteLock

 1 package com.ietree.basicskill.mutilthread.lock;
 2 
 3 import java.util.concurrent.locks.ReentrantReadWriteLock;
 4 
 5 /**
 6  * Created by Administrator on 2017/5/17.
 7  */
 8 public class UseReentrantReadWriteLock {
 9 
10     private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
11     private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
12     private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
13 
14     public void read(){
15         try {
16             readLock.lock();
17             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
18             Thread.sleep(3000);
19             System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
20         } catch (Exception e) {
21             e.printStackTrace();
22         } finally {
23             readLock.unlock();
24         }
25     }
26 
27     public void write(){
28         try {
29             writeLock.lock();
30             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
31             Thread.sleep(3000);
32             System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
33         } catch (Exception e) {
34             e.printStackTrace();
35         } finally {
36             writeLock.unlock();
37         }
38     }
39 
40     public static void main(String[] args) {
41 
42         final UseReentrantReadWriteLock urrw = new UseReentrantReadWriteLock();
43 
44         Thread t1 = new Thread(new Runnable() {
45             @Override
46             public void run() {
47                 urrw.read();
48             }
49         }, "t1");
50         Thread t2 = new Thread(new Runnable() {
51             @Override
52             public void run() {
53                 urrw.read();
54             }
55         }, "t2");
56         Thread t3 = new Thread(new Runnable() {
57             @Override
58             public void run() {
59                 urrw.write();
60             }
61         }, "t3");
62         Thread t4 = new Thread(new Runnable() {
63             @Override
64             public void run() {
65                 urrw.write();
66             }
67         }, "t4");
68 
69 //        t1.start();
70 //        t2.start();
71 
72 //        t1.start(); // R
73 //        t3.start(); // W
74 
75         t3.start();
76         t4.start();
77     }
78 }

三、Condition

 1 package com.ietree.basicskill.mutilthread.lock;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.Lock;
 5 import java.util.concurrent.locks.ReentrantLock;
 6 
 7 /**
 8  * Created by Administrator on 2017/5/17.
 9  */
10 public class UseCondition {
11     private Lock lock = new ReentrantLock();
12     private Condition condition = lock.newCondition();
13 
14     public void method1(){
15         try {
16             lock.lock();
17             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入等待状态..");
18             Thread.sleep(3000);
19             System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁..");
20             condition.await();    // Object wait
21             System.out.println("当前线程:" + Thread.currentThread().getName() +"继续执行...");
22         } catch (Exception e) {
23             e.printStackTrace();
24         } finally {
25             lock.unlock();
26         }
27     }
28 
29     public void method2(){
30         try {
31             lock.lock();
32             System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..");
33             Thread.sleep(3000);
34             System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒..");
35             condition.signal();        //Object notify
36         } catch (Exception e) {
37             e.printStackTrace();
38         } finally {
39             lock.unlock();
40         }
41     }
42 
43     public static void main(String[] args) {
44 
45         final UseCondition uc = new UseCondition();
46         Thread t1 = new Thread(new Runnable() {
47             @Override
48             public void run() {
49                 uc.method1();
50             }
51         }, "t1");
52         Thread t2 = new Thread(new Runnable() {
53             @Override
54             public void run() {
55                 uc.method2();
56             }
57         }, "t2");
58         t1.start();
59 
60         t2.start();
61     }
62 }

四、ManyCondition

  1 package com.ietree.basicskill.mutilthread.lock;
  2 
  3 import java.util.concurrent.locks.Condition;
  4 import java.util.concurrent.locks.ReentrantLock;
  5 
  6 /**
  7  * Created by Administrator on 2017/5/17.
  8  */
  9 public class UseManyCondition {
 10     private ReentrantLock lock = new ReentrantLock();
 11     private Condition c1 = lock.newCondition();
 12     private Condition c2 = lock.newCondition();
 13 
 14     public void m1(){
 15         try {
 16             lock.lock();
 17             System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m1等待..");
 18             c1.await();
 19             System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m1继续..");
 20         } catch (Exception e) {
 21             e.printStackTrace();
 22         } finally {
 23             lock.unlock();
 24         }
 25     }
 26 
 27     public void m2(){
 28         try {
 29             lock.lock();
 30             System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m2等待..");
 31             c1.await();
 32             System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m2继续..");
 33         } catch (Exception e) {
 34             e.printStackTrace();
 35         } finally {
 36             lock.unlock();
 37         }
 38     }
 39 
 40     public void m3(){
 41         try {
 42             lock.lock();
 43             System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m3等待..");
 44             c2.await();
 45             System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m3继续..");
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } finally {
 49             lock.unlock();
 50         }
 51     }
 52 
 53     public void m4(){
 54         try {
 55             lock.lock();
 56             System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒..");
 57             c1.signalAll();
 58         } catch (Exception e) {
 59             e.printStackTrace();
 60         } finally {
 61             lock.unlock();
 62         }
 63     }
 64 
 65     public void m5(){
 66         try {
 67             lock.lock();
 68             System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒..");
 69             c2.signal();
 70         } catch (Exception e) {
 71             e.printStackTrace();
 72         } finally {
 73             lock.unlock();
 74         }
 75     }
 76 
 77     public static void main(String[] args) {
 78 
 79 
 80         final UseManyCondition umc = new UseManyCondition();
 81         Thread t1 = new Thread(new Runnable() {
 82             @Override
 83             public void run() {
 84                 umc.m1();
 85             }
 86         },"t1");
 87         Thread t2 = new Thread(new Runnable() {
 88             @Override
 89             public void run() {
 90                 umc.m2();
 91             }
 92         },"t2");
 93         Thread t3 = new Thread(new Runnable() {
 94             @Override
 95             public void run() {
 96                 umc.m3();
 97             }
 98         },"t3");
 99         Thread t4 = new Thread(new Runnable() {
100             @Override
101             public void run() {
102                 umc.m4();
103             }
104         },"t4");
105         Thread t5 = new Thread(new Runnable() {
106             @Override
107             public void run() {
108                 umc.m5();
109             }
110         },"t5");
111 
112         t1.start();    // c1
113         t2.start();    // c1
114         t3.start();    // c2
115 
116 
117         try {
118             Thread.sleep(2000);
119         } catch (InterruptedException e) {
120             e.printStackTrace();
121         }
122 
123         t4.start();    // c1
124         try {
125             Thread.sleep(2000);
126         } catch (InterruptedException e) {
127             e.printStackTrace();
128         }
129         t5.start();    // c2
130 
131     }
132 }

 

以上是关于.net 多线程 lock锁的问题的主要内容,如果未能解决你的问题,请参考以下文章

一种多线程变量区域锁的实现方法

Java多线程-Lock锁的使用,以及生产者和消费者的实现

多线程JUC并发篇常见面试详解

多线程中的锁的几种用法总结

Java学习笔记—多线程(java.util.concurrent.locks包,转载)

多线程死锁