sync_test.go 683 B

123456789101112131415161718192021222324252627282930313233
  1. package test
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. )
  7. func TestSync(t *testing.T) {
  8. // 创建一个对象池,New 是当对象池为空时提供的对象
  9. pool := sync.Pool{
  10. New: func() interface{} {
  11. fmt.Println("Creating a new instance.")
  12. return "New Object"
  13. },
  14. }
  15. // 从池中获取对象
  16. obj1 := pool.Get().(string)
  17. fmt.Println("Got:", obj1)
  18. // 放回对象池
  19. pool.Put("Reused Object")
  20. // 再次从池中获取对象,这次会使用池中已有的对象
  21. obj2 := pool.Get().(string)
  22. fmt.Println("Got:", obj2)
  23. // 第三次从池中获取对象,池已为空,会调用 New 函数创建新对象
  24. obj3 := pool.Get().(string)
  25. fmt.Println("Got:", obj3)
  26. }