我如何将下面的代码转换为Go,您可以在下面看到我的尝试,但是因为我正在等待一个键输入,该代码将始终返回20000java 将输出不同结果的位置。我知道两者都有竞争条件,但我只想知道翻译。
爪哇
public class Counting {
public static void main(String[] args) throws InterruptedException {
class Counter {
private int count = 0;
public void increment() { ++count; }
public int getCount() { return count; }
}
final Counter counter = new Counter();
class CountingThread extends Thread {
public void run() {
for(int x = 0; x < 10000; ++x)
counter.increment();
}
}
CountingThread t1 = new CountingThread();
CountingThread t2 = new CountingThread();
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(counter.getCount());
}
}
这是我的尝试:
import (
"fmt"
)
type Counting struct {
count int
}
var counter = Counting{}
func (c *Counting) increment() {
c.count++
}
func (c *Counting) getCount() int {
return c.count
}
func CountingThread() {
for i := 0; i < 10000; i++ {
counter.increment()
}
}
func main() {
go CountingThread()
go CountingThread()
var input string
fmt.Scanln(&input)
fmt.Println(counter.getCount())
}
相关分类