我如何將下面的代碼轉(zhuǎn)換為Go,您可以在下面看到我的嘗試,但是因?yàn)槲艺诘却粋€(gè)鍵輸入,該代碼將始終返回20000java 將輸出不同結(jié)果的位置。我知道兩者都有競(jìng)爭(zhēng)條件,但我只想知道翻譯。爪哇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())}
添加回答
舉報(bào)
0/150
提交
取消