Results 1 to 3 of 3
  1. #1
    nikkka is offline Member
    Join Date
    Mar 2011
    Posts
    45
    Rep Power
    0

    Default multithreading basics

    Threads in this program should interfere with each other because of accessing the same array at the time. So output should rather look like "12112" than like "22222", right? The thing is that output IS actually "22222", but I cannot see the reason.
    Java Code:
    public class Threads {
    	public static void main(String[] args) {
    		PrintTask1 thread1 = new PrintTask1();
    		PrintTask2 thread2 = new PrintTask2();
    		thread1.run();      //These two threads should interfere
    		thread2.run();      //with each other and provide wrong
    		Array.show();      //output in this line.
    	}
    }
    
    class PrintTask1 implements Runnable {      //Nothing complicated, just
    	public void run() {                  //modifying the array
    		for(int i=0;i<5;i++) {
    			Array.array[i]=1;
    		}
    	}
    }
    class PrintTask2 implements Runnable {      //The same
    	public void run() {
    		for(int i=0;i<5;i++) {
    			Array.array[i]=2;
    		}
    	}
    }
    class Array {            //Data array, or in this case, so called "buffer"
    	public static int[] array = new int[5];
    	public static void show() {
    		for(int i=0;i<5;i++)
    			System.out.println(array[i]);
    	}
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,985
    Rep Power
    9

    Default

    You aren't actually creating any new Threads. Instances of Runnable are not automatically run on a new Thread.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    nikkka is offline Member
    Join Date
    Mar 2011
    Posts
    45
    Rep Power
    0

    Default

    Oh... yes... Is this code right? Because it doesn't work either...
    Java Code:
    		Thread thread1 = new Thread(new PrintTask1());
    		Thread thread2 = new Thread(new PrintTask2());
    		thread1.run();
    		thread2.run();

Similar Threads

  1. Multithreading Gui
    By BUGSIE91 in forum Threads and Synchronization
    Replies: 7
    Last Post: 10-13-2010, 02:20 PM
  2. Want to know about Multithreading.
    By Chetans in forum Threads and Synchronization
    Replies: 1
    Last Post: 03-19-2010, 07:50 AM
  3. Really Basics
    By Taluntain in forum New To Java
    Replies: 16
    Last Post: 10-08-2009, 09:43 AM
  4. Basics
    By AKP in forum New To Java
    Replies: 7
    Last Post: 05-23-2008, 12:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •