首页 \ 问答 \ 单例实例(Singleton Instance)

单例实例(Singleton Instance)

我知道有很多方法来实现一个线程安全的单例模式,比如(Double Check Locking,静态只读方法,锁定方法),但我只是在代码的下面

static void Main(string[] args)
{           
    for (int i = 0; i <= 100; i++)
    {
        Thread t = new Thread(new ParameterizedThreadStart(doSome));
        t.Start(null);               
    }
    Console.ReadLine();
}

private static void doSome(object obj)
{           
    MyReadOnly obj1 = MyReadOnly.getInstance;
    Console.WriteLine(obj1.GetHashCode().ToString());
}   

class MyReadOnly
{
    private static  MyReadOnly instance  = new MyReadOnly();
    int counter = 0;

   // static MyReadOnly()
   // {
   // }  treat is as commented code.

    public static MyReadOnly getInstance { get { return instance; } }
    private MyReadOnly()
    {
        Console.WriteLine((++counter).ToString());
    }       
}

当我看到这个程序的输出时,我看到的只是单个对象的创建(因为相同的哈希码)

如何证明这段代码不是线程安全的?

编辑

删除造成一些混淆的静态构造函数


I know there are lot of ways to implement a thread safe singleton pattern like (Double Check Locking , static readonly method, lock method) but i just tried below code

static void Main(string[] args)
{           
    for (int i = 0; i <= 100; i++)
    {
        Thread t = new Thread(new ParameterizedThreadStart(doSome));
        t.Start(null);               
    }
    Console.ReadLine();
}

private static void doSome(object obj)
{           
    MyReadOnly obj1 = MyReadOnly.getInstance;
    Console.WriteLine(obj1.GetHashCode().ToString());
}   

class MyReadOnly
{
    private static  MyReadOnly instance  = new MyReadOnly();
    int counter = 0;

   // static MyReadOnly()
   // {
   // }  treat is as commented code.

    public static MyReadOnly getInstance { get { return instance; } }
    private MyReadOnly()
    {
        Console.WriteLine((++counter).ToString());
    }       
}

when i see the output of this program , i see just single object created (because of same hashcode)

how to prove that this code is not thread safe?

EDIT

removing static constructor which causes some confusion


原文:https://stackoverflow.com/questions/4050428
更新时间:2022-10-07 08:10

最满意答案

好的,我终于找到了一个解决方案,如何在Mac OS X中围绕视图拖动Label或TextField(NSTextField)控件。 我已经完成了解决方案:

在ViewController类中创建一个属性

class ViewController:  NSViewController {
    var mouseDownLocation: CGPoint?

}

在覆盖mouseDown事件中

var mouseDownEvent: NSEvent?


@IBAction override func mouseDown(theEvent: NSEvent) {

    var event_location: NSPoint!
    event_location = theEvent.locationInWindow

    var cntrl_id = NSTextField()
    var cntrl_frame = NSRect()
    var cntrl_name = String()
    var cntrl_value = String()
    var hit = Bool()

    for view in self.view.subviews as [NSView] {
        if let ct = view as? NSTextField {
            cntrl_name = ct.identifier!
            cntrl_id = ct
            cntrl_frame = ct.frame
            cntrl_value = ct.stringValue
            hit = cntrl_frame.contains(event_location)
            if hit {
                controlToMove = cntrl_id
                lastLocation = controlToMove?.frame.origin
                break
            }
        }
    }

    //figure out the difference of where the mouse went down at in the
    //control frame in relation to the control frame origin
    let dx = event_location.x - (controlToMove?.frame.origin.x)!
    let dy = event_location.y - (controlToMove?.frame.origin.y)!
    let mouseDownInCntrlFrame = CGPoint(x: dx, y: dy)
    mouseDownLocation = mouseDownInCntrlFrame

}

现在在覆盖mouseDragged事件中

@IBAction override func mouseDragged(theEvent: NSEvent) {

    let dragPoint = theEvent.locationInWindow

    if controlToMove != nil {

        var cntrl_location = CGPoint();
        cntrl_location.x = controlToMove!.frame.origin.x
        cntrl_location.y = controlToMove!.frame.origin.y
        print( "cntrl_location X,Y = \(cntrl_location)" )

        let previousLocation = cntrl_location

        var location = CGPoint()
        location = dragPoint
        location.x -= (mouseDownLocation?.x)!
        location.y -= (mouseDownLocation?.y)!

        var delta_x = CGFloat()
        var delta_y = CGFloat()
        delta_x = location.x - previousLocation.x
        delta_y = location.y - previousLocation.y

        // move label
        cntrl_location = CGPointMake(location.x + delta_x, location.y + delta_y);

        controlToMove!.frame.origin.x = cntrl_location.x
        controlToMove!.frame.origin.y = cntrl_location.y

    }

}

这将允许您在单击并拖动的视图周围拖动任何NSTextField。 它并不像我想的那样平滑,因为你在视图中拖动它时只需要一点希望控件。 但是考虑到互联网上没有其他任何关于如何拖动OS X控件的信息(有一些关于如何拖动图像的博客和信息 - 但即使是那些更像是拖放式解决方案)快速浏览视图这是一个有效的解决方案。 我相信一位经验丰富的OS X Xcode大师可以改进这个解决方案 - 如果OS X开发人员希望提供一些经验,我欢迎对此解决方案进行改进。


Okay I have a solution finally to the question how do you drag a Label or TextField (NSTextField) control in Mac OS X around a view. I have finalized the solution:

In the ViewController class create a property

class ViewController:  NSViewController {
    var mouseDownLocation: CGPoint?

}

In the override mouseDown event

var mouseDownEvent: NSEvent?


@IBAction override func mouseDown(theEvent: NSEvent) {

    var event_location: NSPoint!
    event_location = theEvent.locationInWindow

    var cntrl_id = NSTextField()
    var cntrl_frame = NSRect()
    var cntrl_name = String()
    var cntrl_value = String()
    var hit = Bool()

    for view in self.view.subviews as [NSView] {
        if let ct = view as? NSTextField {
            cntrl_name = ct.identifier!
            cntrl_id = ct
            cntrl_frame = ct.frame
            cntrl_value = ct.stringValue
            hit = cntrl_frame.contains(event_location)
            if hit {
                controlToMove = cntrl_id
                lastLocation = controlToMove?.frame.origin
                break
            }
        }
    }

    //figure out the difference of where the mouse went down at in the
    //control frame in relation to the control frame origin
    let dx = event_location.x - (controlToMove?.frame.origin.x)!
    let dy = event_location.y - (controlToMove?.frame.origin.y)!
    let mouseDownInCntrlFrame = CGPoint(x: dx, y: dy)
    mouseDownLocation = mouseDownInCntrlFrame

}

Now in the override mouseDragged event

@IBAction override func mouseDragged(theEvent: NSEvent) {

    let dragPoint = theEvent.locationInWindow

    if controlToMove != nil {

        var cntrl_location = CGPoint();
        cntrl_location.x = controlToMove!.frame.origin.x
        cntrl_location.y = controlToMove!.frame.origin.y
        print( "cntrl_location X,Y = \(cntrl_location)" )

        let previousLocation = cntrl_location

        var location = CGPoint()
        location = dragPoint
        location.x -= (mouseDownLocation?.x)!
        location.y -= (mouseDownLocation?.y)!

        var delta_x = CGFloat()
        var delta_y = CGFloat()
        delta_x = location.x - previousLocation.x
        delta_y = location.y - previousLocation.y

        // move label
        cntrl_location = CGPointMake(location.x + delta_x, location.y + delta_y);

        controlToMove!.frame.origin.x = cntrl_location.x
        controlToMove!.frame.origin.y = cntrl_location.y

    }

}

This will let you drag any NSTextField around the view that you click down on and drag. It is not quite as smooth as I would like there is just a bit of hoping of the control as you drag it around the view. But considering that there is no other information anywhere on the internet on how to drag an OS X control (there are a couple of blogs and information on how to drag an image - but even those are more of a drag and drop type solution) in swift around a view this is a solution that works. I am sure an experienced OS X Xcode guru could improve on this solution - I welcome a refinement to this solution if some experience OS X developer wishes to contribute.

相关问答

更多
  • Visual Studio仅在Windows上运行,因此您需要虚拟化软件(VMWare Fusion或Parallels)或Boot Camp。 WINE允许一些Windows程序在OS X上运行,但我怀疑你是否想要将它用于Visual Studio,即使它确实有效。 Visual Studio only runs on Windows, so you would need virtualisation software (VMWare Fusion or Parallels) or Boot Camp. ...
  • 我建议您将调试器连接到非开发机器上的应用程序。 这可以通过运行lldb 来实现,然后在提示再次准备好时process launch 。 这将作为标准调试器使用,可以帮助您更完整地理解错误并调试问题。 关于为什么它不能在另一台机器上运行,因此使用调试器获取有关该问题的信息是这种情况下的最佳选择。 I'd recommend that you attach the debugger to the application on your non-dev machine. This can ...
  • 更新: 在JDK 1.7上运行IDEA 12(在Info.plist JVMVersion更改为1.7* )后,请确保您的环境中有LANG=en_US.UTF-8 ,请参阅相关的Java问题: http://java.net/jira/browse/MACOSX_PORT-165 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7187821 有关调试启动器问题, 请参阅此线程 。 还请注意,Mac上的GUI应用程序无法访问您的终端环境。 如果您定义了一 ...
  • 好的,我终于找到了一个解决方案,如何在Mac OS X中围绕视图拖动Label或TextField(NSTextField)控件。 我已经完成了解决方案: 在ViewController类中创建一个属性 class ViewController: NSViewController { var mouseDownLocation: CGPoint? } 在覆盖mouseDown事件中 var mouseDownEvent: NSEvent? @IBAction override func m ...
  • Mac OSX建立在BSD之上。 http://en.wikipedia.org/wiki/OS_X 在我看来,Linux类很好,可以让你对命令行感到满意。 需要注意的是,命令的输出或可用性或选项存在差异。 实例是“ps”。 系统库,文件夹结构也不同。 另外请注意,如果您曾在* NIX服务器计算机上工作,那么这些计算机总是会是linux。 请注意,现在没有OSX服务器了。 Mac OSX is built on top of BSD. http://en.wikipedia.org/wiki/OS_X Li ...
  • 似乎我自己找到了解决方案。 我必须将AVCaptureVideoPreviewLayer附加到CALayer,然后将CALayer添加到CustomView中。 我可以通过以下方式实现这一目标: let renderLayer = CALayer() layer.wantsLayer = true // layer is a NSView layer.layer = renderLayer // Initialize AVCaptureSession and other stuff... It ...
  • if userNametext.stringValue == "" { //Action } 如此处所示,您可以使用stringValue属性访问NSTextField的文本,该属性也可用于修改文本。 if userNametext.stringValue == "" { //Action } As seen here you can access the text of the NSTextField using the stringValue property, which can ...
  • 根据您运行的OSX版本,最好的选择可能是原生的Mac X11 Distribution。 它位于安装光盘上(或者,如果你像我一样,你通过App Store获得Lion,默认情况下它可以在Utilities文件夹中找到)。 启动它(应用程序>实用程序> X11)会打开一个特定的X11 x终端,您可以使用它来转发到您的Ubuntu系统。 答案1中的链接已经很老了,我发现这个链接更有帮助: http : //www.craigryder.com/linux-ubuntudebetc/x11-forwarding- ...
  • 我确实弄清楚如何确定在视图的mouseDown事件中是否单击了我的一个NSTextField控件: @IBAction override func mouseDown(theEvent: NSEvent) { var event_location: NSPoint! event_location = theEvent.locationInWindow self.mouseDownEvent = theEvent var cntrl_id = NSTextField() ...
  • 使ViewController符合协议NSTextDelegate 。 将ViewController指定为TextField委托。 实现controlTextDidChange方法。 import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)