C#中的原子操作
2021-06-09 14:03
标签:ram class 结果 import java name 简单 sys lan 某天,我同学发给我这样一道题。看着还是挺简单的,我当时 就想到了线程等待。 使用AutoResetEvent类来两个线程互相等待,互相通知 事实证明,这个方法是可行的。原理就是线程2等待线程1事件的发生,线程1等待线程2事件的发生。因为线程1是先跑起来的,就保证了这样一种操作的可行性。 最后运行结果如下: 但个人觉得不够理想。目前还在学习阶段,也说不起为啥不理想,可能 就是单纯的认为吧。 最后请教了同学,看他的做法。他给出的java代码如下 C#中的原子操作 标签:ram class 结果 import java name 简单 sys lan 原文地址:https://www.cnblogs.com/zhaotianff/p/10649700.html 1 class Program
2 {
3 static AutoResetEvent autoResetEvent1 = new AutoResetEvent(false);
4 static AutoResetEvent autoResetEvent2 = new AutoResetEvent(false);
5
6 static void Main(string[] args)
7 {
8 new Thread(Print1).Start();
9 new Thread(Print2).Start();
10 }
11
12 static void Print1()
13 {
14 for (int i = 1; i 100; i+=2)
15 {
16 Console.WriteLine(i.ToString() + " at thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
17 autoResetEvent1.Set();
18 autoResetEvent2.WaitOne();
19 }
20 }
21
22 static void Print2()
23 {
24 for (int i = 2; i 100; i+=2)
25 {
26 autoResetEvent1.WaitOne();
27 Console.WriteLine(i.ToString() + " at thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
28 autoResetEvent2.Set();
29 }
30 }
31 }
1 import java.util.concurrent.atomic.AtomicInteger;
2
3 public class Exeaple {
4
5 private static AtomicInteger aInt = new AtomicInteger(0);
6
7 public static void main(String[] args) {
8 Thread1 thread1 = new Thread1("thread - 1");
9 Thread2 thread2 = new Thread2("thread - 2");
10 thread2.start();
11 thread1.start();
12 }
13
14 static class Thread1 extends Thread {
15 private String threadName;
16 public Thread1(String threadName) {
17 this.threadName = threadName;
18 }
19 @Override
20 public void run() {
21 while (aInt.get() ) {
22 if (aInt.get() % 2 == 1) {
23 System.out.println(threadName + ":" + aInt.get());
24 aInt.incrementAndGet();
25 }
26 }
27 }
28 }
29
30 static class Thread2 extends Thread {
31 private String threadName;
32 public Thread2(String threadName) {
33 this.threadName = threadName;
34 }
35 @Override
36 public void run() {
37 while (aInt.get() ) {
38 if (aInt.get() % 2 == 0) {
39 System.out.println(threadName + ":" + aInt.get());
40 aInt.incrementAndGet();
41 }
42 }
43 }
44 }
45
46 }
下一篇:C#中一些注意问题