CopyOnWriteArrayList in Java

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayTest {
	CopyOnWriteArrayList<String> basket = new CopyOnWriteArrayList<String>();
	
	Thread fruit;
	Thread vegatable;
	Thread bean;
	Thread keepSize;
	Thread takeFromBasket;
	
	public CopyOnWriteArrayTest() {
		fruit = new Thread(new Runnable() {
			String [] fruit = {
					"Apple",
					"Apricot",
					"Avocado",
					"Banana",
					"Blackberry",
					"Orange"
			};
			@Override
			public void run() {
				while(true)
				{					
					try {
						for(int i = 0; i < fruit.length; i++)
							basket.add(fruit[i]);
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		fruit.start();
		
		vegatable = new Thread(new Runnable() {
			String [] vegatable = {
					"Bok choy",
					"Cabbage",
					"Catsear",
					"Celery",
					"Spinach"
			};
			@Override
			public void run() {
				while(true)
				{	
					try {
						for(int i = 0; i < vegatable.length; i++)
							basket.add(vegatable[i]);
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		vegatable.start();
		
		bean = new Thread(new Runnable() {
			String [] bean = {
					"pea",
					"ricebean",
					"black-eyed pea",
					"soybean",
					"peanuts"
			};
			@Override
			public void run() {
				while(true)
				{
					try {
						for(int i = 0; i < bean.length; i++)
						{
							if(bean[i] == "peanuts")
								System.out.println("Peanuts has been added.");
							basket.add(bean[i]);
						}
						
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		bean.start();
		
		keepSize = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true)
				{
					if(basket.size() > 20)
						basket.remove(0);
					
					if(Thread.interrupted())
						return;
				}
			}
		});
		keepSize.start();
		
		takeFromBasket = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true)
				{
					try {
						int i = basket.indexOf("peanuts");
						if(i != -1)
						{
							basket.remove("peanuts");
							System.out.println("Peanut is found. Size: " + basket.size());
						}
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		takeFromBasket.start();
	}
	
	void Stop()
	{
		fruit.interrupt();
		vegatable.interrupt();
		bean.interrupt();
		keepSize.interrupt();
		takeFromBasket.interrupt();
	}
	public static void main(String[] args) throws InterruptedException {
		CopyOnWriteArrayTest c = new CopyOnWriteArrayTest();
		Thread.sleep(120000);
		c.Stop();
	}

}

ArrayBlockingQueue in Java

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockingQueueTest {
	ArrayBlockingQueue<String> b = new ArrayBlockingQueue<String>(10, true);
	Thread t1;
	Thread t2;
	String text = "India’s recent series of power blackouts, "
			+ "in which 600 million people lost electricity for "
			+ "several days, reminds us of the torrid pace at which "
			+ "populations in the developing world have moved onto "
			+ "the powergrid. Unfortunately, this great transition "
			+ "has been so rapid that infrastructure has mostly been "
			+ "unable to meet demand. India itself has failed to meets "
			+ "its own power capacity addition targets every year since "
			+ "1951. This has left roughly one quarter of the country’s "
			+ "population without any (legal) access to electricity. "
			+ "That’s 300 million people out of a population of 1.2 "
			+ "billion. Indeed, it is the daily attempt of the underserved "
			+ "to access power that may have led to India’s recent grid crash.";
	
	class Writing implements Runnable
	{
		@Override
		public void run() {
			int i = 0;
			String [] p = text.split(" ");
			while(true)
			{
				try {
					b.put(p[i]);
				} catch (InterruptedException e) {
					break;
				}
				i++;
				if(i == p.length)
					i = 0;
			}
		}
	}
	
	class Reading implements Runnable
	{
		@Override
		public void run() {
			while(true)
			{
				try {
					for(int i = 0; i < 5; i++)
					{
						String t = b.poll(500, TimeUnit.MILLISECONDS);
						System.out.print(t + " ");
					}
					Thread.sleep(500);
				} catch (InterruptedException e) {
					break;
				}
			}	
		}
	}
	
	public void Stop()
	{
		t1.interrupt();
		t2.interrupt();
	}
	public ArrayBlockingQueueTest() {
		t1 = new Thread(new Writing());
		t1.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2 = new Thread(new Reading());
		t2.start();
	}
	
	public static void main(String[] args) throws InterruptedException {
		ArrayBlockingQueueTest a = new ArrayBlockingQueueTest();
		Thread.sleep(6000);
		a.Stop();
	}
}

Semaphore in Java

import java.util.concurrent.*;

public class SemaphoreThread {

	static public class runThreadClass implements Runnable
	{
		Semaphore s;
		int i, count;
		public runThreadClass(int i, Semaphore s) {
			this.i = i;
			count = i + 2;
			this.s = s;
		}
		public void run() {
			try {
				s.acquire();
				System.out.println("Thread " + i + ". Work for " + count + " seconds.");
				Thread.sleep(count * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			s.release();
		}
	}
	public static void main(String[] args) {
		final Semaphore s = new Semaphore(4);
		for(int i = 0; i < 10; i++)
			new Thread(new runThreadClass(i + 1, s)).start();
	}
}

CountDownLatch in Java

import java.util.concurrent.*;

public class CountdownThread {

	public static void main(String[] args) {
		final CountDownLatch signal = new CountDownLatch(4);
		
		class runnable implements Runnable
		{
			int id;
			int length;
			
			public runnable(int id, int length) {
				this.id = id;
				this.length = length;
			}

			@Override
			public void run() {
				try {
					System.out.println("Thread " + id + ". Doing something for " + length + " seconds.");
					Thread.sleep(length * 1000);
					signal.countDown();
					System.out.println("Thread " + id + ". Done. Waiting now.");
					signal.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				System.out.println("Thread " + id + " done.");
			}
		}
		
		new Thread(new runnable(1, 4)).start();
		new Thread(new runnable(2, 3)).start();
		new Thread(new runnable(3, 2)).start();
		new Thread(new runnable(4, 1)).start();
	}
}

Threads using Executors in Java

import java.util.concurrent.*;

public class ThreadsWithExecutor {
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread1");
			}
		});
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread2");
			}
		});
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread3");
			}
		});
		
		Future<Integer> f = service.submit(new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {				
				return 100;
			}
		});
		
		try {
			System.out.println(f.get());
		} catch (Exception e) {
			e.printStackTrace();
		}

		service.shutdown();
		try {
			service.awaitTermination(100, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("\nScheduling Thread");
		ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10);
		scheduledExecutor.schedule(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("This thread runs after 5 seconds wait");
			}
		}, 5, TimeUnit.SECONDS);
		scheduledExecutor.schedule(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("This thread runs after 7 seconds wait");
			}
		}, 7, TimeUnit.SECONDS);
		scheduledExecutor.shutdown();
	}
}

Threading in Java

import java.util.Random;

public class ThreadTutorial {
	
	static class ThreadClass1
	{
		boolean stop = false;
		void DoSomething()
		{
			Random r = new Random();
			r.nextInt();
		}
		
		public synchronized void thinking() 
		{
			DoSomething();
			
			System.out.println("thinking for 2 seconds");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		public synchronized void reading()
		{
			DoSomething();
			
			System.out.println("reading for 1 seconds");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public ThreadClass1()
		{
			Thread t1 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						thinking();
						if(stop != false)
							break;
					}
				}
			});
			t1.start();
			
			Thread t2 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						reading();
						if(stop != false)
							break;
					}
				}
			});
			t2.start();
			
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stop = true;
			
			try {
				t1.join();
				t2.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class ThreadClass2
	{
		boolean stop = false;
		Object o1 = new Object();
		Object o2 = new Object();
		
		void DoSomething()
		{
			Random r = new Random();
			r.nextInt();
		}
		
		public void readingHarddrive() 
		{
			DoSomething();
			
			synchronized (o1) {
				System.out.println("reading hard drive for 2 seconds");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		public void writingHarddrive()
		{
			DoSomething();
			
			synchronized (o1) {
				System.out.println("writing hard drive for 1 seconds");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
			}
		}

		public void readingDatabase() 
		{
			DoSomething();
			
			synchronized (o2) {
				System.out.println("reading database for 5 seconds");
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
			}
		}
		public void writingDatabase()
		{
			DoSomething();
			
			synchronized (o2) {
				System.out.println("writing database for 4 seconds");
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}				
			}
		}
		
		public ThreadClass2()
		{
			Thread t1 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						readingDatabase();
						if(stop != false)
							break;
					}
				}
			});
			t1.start();
			
			Thread t2 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						writingDatabase();
						if(stop != false)
							break;
					}
				}
			});
			t2.start();
			
			Thread t3 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						readingHarddrive();
						if(stop != false)
							break;
					}
				}
			});
			t3.start();
			
			Thread t4 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						writingHarddrive();
						if(stop != false)
							break;
					}
				}
			});
			t4.start();
			
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stop = true;
			
			try {
				t1.join();
				t2.join();
				t3.join();
				t4.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws InterruptedException {
		new ThreadClass1();
		System.out.println("------------------------------------------------------");
		new ThreadClass2();
	}
}			

ToString in C#

class Person
{
    string fname;
    string lname;
    public Person(string fname, string lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public override string ToString()
    {
        return fname + " " + lname;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person("John", "Smith");
        Console.WriteLine(p);
    }
}
Posted in C#

toString in Java

public class ToStringTest {
	static class Person
	{
		String fname;
		String lname;
		public Person(String fname, String lname) {
			this.fname = fname;
			this.lname = lname;
		}
		
		@Override
		public String toString()
		{
			return fname + " " + lname;
		}
	}
	public static void main(String[] args) {
		Person p = new Person("John", "Smith");
		System.out.println(p);
	}
}

HashCode in C#

Another hashcode example

class Program
{
    class Person
    {
        public Person(String fname, String lname)
        {
            this.fname = fname;
            this.lname = lname;
        }

        String fname;
        String lname;

        public int hashCode()
        {
            return (fname.GetHashCode() * 1021) ^ lname.GetHashCode();
        }

        public bool equals(Object obj)
        {
            return this.fname.Equals(((Person)obj).fname) &&
                    this.lname.Equals(((Person)obj).lname);
        }
    }

    class Point
    {
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        int x;
        int y;

        public int hashCode()
        {
            return (x * 31) ^ y;
        }

        public bool equals(Object obj)
        {
            return x == ((Point)obj).x &&
                    y == ((Point)obj).y;
        }
    }

    static char[] getLowerCase()
    {
        char[] temp = new char[26];
        for (int i = 0; i < 26; i++)
            temp[i] = (char)(i + 97);
        return temp;
    }

    static char[] getUpperCase()
    {
        char[] temp = new char[26];
        for (int i = 0; i < 26; i++)
            temp[i] = (char)(i + 65);
        return temp;
    }

    static String getName(char[] lower, char[] upper)
    {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        int count = r.Next(10);
        for (int j = 0; j < count; j++)
        {
            int index = r.Next(25);
            if (j == 0)
                sb.Append(upper[index]);
            else
                sb.Append(lower[index]);
        }
        return sb.ToString();
    }

    static void AnalyzePerson()
	{
		char [] lower = getLowerCase();
		char [] upper = getUpperCase();
		Hashtable table = new Hashtable();
		Person []list = new Person[500000];

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
		for(int i = 0; i < 500000; i++)
		{
			String fname = getName(lower, upper);
			String lname = getName(lower, upper);
			Person p = new Person(fname, lname);
			table.Add(p, i);
			list[i] = p;
		}
        stopwatch.Stop();
		Console.WriteLine("putting: " + stopwatch.ElapsedMilliseconds + " ms");

        stopwatch.Restart();
		for(int i = 0; i < 500000; i++)
		{
			Person p = list[i];
			object o = table[p];
		}
        stopwatch.Stop();
        Console.WriteLine("getting: " + stopwatch.ElapsedMilliseconds + " ms");
	}

    static void AnalyzePoint()
	{
		Hashtable table = new Hashtable();
		Point []list = new Point[500000];
		Random r = new Random();
		
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
		for(int i = 0; i < 500000; i++)
		{
			Point p = new Point(r.Next(50), r.Next(100));
			table.Add(p, i);
			list[i] = p;
		}
		stopwatch.Stop();
		Console.WriteLine("putting: " + stopwatch.ElapsedMilliseconds + " ms");
		
        stopwatch.Restart();
        for(int i = 0; i < 500000; i++)
		{
			Point p = list[i];
			object o = table[p];
		}
		stopwatch.Stop();
		Console.WriteLine("getting: " + stopwatch.ElapsedMilliseconds + " ms");
	}
    static void Main(string[] args)
    {
        AnalyzePoint();
        AnalyzePerson();
    }
}

HashCode in Java

import java.util.Hashtable;
import java.util.Random;

public class HashCode {
	static class Person
	{
		public Person(String fname, String lname) {
			this.fname = fname;
			this.lname = lname;
		}

		String fname;
		String lname;
		
		public int hashCode()
		{
			return (fname.hashCode() * 1021) ^ lname.hashCode();
		}
		
		public boolean equals(Object obj)
		{
			return this.fname.equals(((Person)obj).fname) &&
					this.lname.equals(((Person)obj).lname);
		}
	}
	
	static class Point
	{
		public Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
		int x;
		int y;
		
		public int hashCode()
		{
			return (x * 31) ^ y;
		}
		
		public boolean equals(Object obj)
		{
			return x == ((Point)obj).x &&
					y == ((Point)obj).y;
		}
	}
	
	static Character [] getLowerCase()
	{
		Character []temp = new Character[26];
		for(int i = 0; i < 26; i++)
			temp[i] = (char)(i + 97);
		return temp;
	}
	
	static Character [] getUpperCase()
	{
		Character []temp = new Character[26];
		for(int i = 0; i < 26; i++)
			temp[i] = (char)(i + 65);
		return temp;
	}
	
	static String getName(Character[] lower, Character[] upper)
	{
		Random r = new Random();
		StringBuilder sb = new StringBuilder();
		int count = r.nextInt(10);
		for(int j = 0; j < count; j++)
		{
			int index = r.nextInt(25);
			if(j == 0)
				sb.append(upper[index]);
			else
				sb.append(lower[index]);
		}
		return sb.toString();
	}
	
	static void AnalyzePerson()
	{
		Character [] lower = getLowerCase();
		Character [] upper = getUpperCase();
		Hashtable<Person, Integer> table = new Hashtable<Person, Integer>();
		Person []list = new Person[500000];
		long pastTime = System.currentTimeMillis();
		for(int i = 0; i < 500000; i++)
		{
			String fname = getName(lower, upper);
			String lname = getName(lower, upper);
			Person p = new Person(fname, lname);
			table.put(p, i);
			list[i] = p;
		}
		long currentTime = System.currentTimeMillis();
		System.out.println("putting: " + (currentTime - pastTime));
		
		pastTime = System.currentTimeMillis();
		for(int i = 0; i < 500000; i++)
		{
			Person p = list[i];
			table.get(p);
		}
		currentTime = System.currentTimeMillis();
		System.out.println("getting: " + (currentTime - pastTime));
	}
	
	static void AnalyzePoint()
	{
		Hashtable<Point, Integer> table = new Hashtable<Point, Integer>();
		Point []list = new Point[500000];
		Random r = new Random();
		long pastTime = System.currentTimeMillis();
		for(int i = 0; i < 500000; i++)
		{
			Point p = new Point(r.nextInt(50), r.nextInt(100));
			table.put(p, i);
			list[i] = p;
		}
		long currentTime = System.currentTimeMillis();
		System.out.println("putting: " + (currentTime - pastTime));
		
		pastTime = System.currentTimeMillis();
		for(int i = 0; i < 500000; i++)
		{
			Point p = list[i];
			table.get(p);
		}
		currentTime = System.currentTimeMillis();
		System.out.println("getting: " + (currentTime - pastTime));
	}
	public static void main(String[] args) {
		AnalyzePoint();
		AnalyzePerson();
	}
}