- Java MultiThreading Code Error
- class ThreadDemo {
- public static void main(String args[]) {
- try{
- int [] arr = new int[10] ;
- for(int i = 0 ; i < 10 ; i++)
- arr[i] = i ;
- for(int c =0 ; c < 2 ; c++){
- for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
- System.out.println(arr[i]);
- for(int j = 0 ; j < 5 ; j++) //I want to run it on another thread
- System.out.println(arr[j]);
- }
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- }
- }
- }
- class ThreadDemo {
- public static void main(String args[]) {
- try{
- int [] arr = new int[10] ;
- for(int i = 0 ; i < 10 ; i++)
- arr[i] = i ;
- for(int c =0 ; c < 2 ; c++){
- Thread thread1 = new Thread () {
- public void run () {
- for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
- System.out.println(arr[i]);}
- };
- Thread thread2 = new Thread () {
- public void run () {
- for(int j = 0 ; j < 5 ; j++) //I want to run it on one thread
- System.out.println(arr[j]);}
- };
- }
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- }
- }
- }
- for (int c = 0; c < 2; c++) {
- Thread thread1 = new Thread() {//<- here
- final int[] arr = new int[10];
- class MyThread extends Thread {
- int[] array;
- int iterations;
- public MyThread(int[] arr, int i) {
- array=arr;
- iterations = i;
- }
- @Override
- public void run() {
- for (int i = 0; i < iterations; i++)
- System.out.println(array[i]);
- }
- }
- class ThreadDemo {
- public static void main(String args[]) {
- try {
- int[] arr = new int[10];
- for (int i = 0; i < 10; i++)
- arr[i] = i;
- for (int c = 0; c < 2; c++) {
- MyThread thread1 = new MyThread(arr, 3);
- MyThread thread2 = new MyThread(arr, 5);
- thread1.start();
- thread2.start();
- }
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- }
- }
- }
- Thread t = new Thread(new Runnable() {
- public void run() {
- }
- });
- t.start();