Threading in Java and C#: A Focused Language Comparison


Threading in Java and C#: A Focused Language Comparison cover page
Threading in Java and C#: A Focused Language Comparison Shannon Hardt Overview Both Java and .NET have built-in support for threads. In Java, this support is in three main forms: a … … mutex variable is associated with every object; there is a set of methods defined on Object that support coordination of threads; and a set of classes in java.lang that allows programmers to create and manage threads. Similarly, in .NET there is a Monitor (or lock) associated with every object instance. The System.Threading namespace contains …

Threading in Java and C#: A Focused Language Comparison Shannon Hardt Creating & Running Threads There are two main techniques for creating a thread in Java: subclass java.lang.Thread or implement the java.lang.Runnable interface. In both cases, you must implement a method with the following signature: public void run() . When you create the thread and tell it to start, the run method will be executed. A simple example is provided below. In this example, when main is executed, it will create a new thread of control using Counter, which when started, will print “Hello World” ten times and then exit. In C#, the pattern is similar. However, instead of implementing an interface or subclassing Thread, you use a ThreadStart delegate. The delegate is then used to instantiate the Thread object. The ThreadStart delegate requires a void method which takes no parameters. The previous example implemented in C# is provided below. An argument could be made in favor of the C# model, as any method that returns void and accepts no arguments could be run as a new thread without changing the class itself. However, this could potentially lead to problems if a method that was not intended to be thread-safe was used to generate a new thread. Of course, this would not be due to a problem with the language, just its improper use. With Java, implementing Runnable should serve as a reminder to implement public class Counter implements Runnable { private int count; public Counter(int val) { this.count = val; } public void run() { for(int i=0; i < count; i++) System.out.println(”Hello World”); } public static void main(String args[]) { Counter c = new Counter(10); Thread t = new Thread(c); t.start(); } } using System; using System.Threading; namespace SimpleThreadExample { class Counter { private int count; public Counter(int val) { this.count = val; } public void DoCount() { for(int i=0; i < count; i++) System.Console.WriteLine(”Hello World”); } [STAThread] static void Main(String[] args) { Counter c = new Counter(10); Thread t = new Thread(new ThreadStart(c.DoCount)); t.start(); } } } …

Download Threading in Java and C#: A Focused Language Comparison.Pdf

Leave a Reply