When I tried to compile this code, it has one error says

ThreadsDemo.java:37: 'else' without 'if'
else {
^

I don't know what's wrong with that exactly?

import java.util.*;

class A extends Thread {
    private static int counter=0;
    private final int id=++counter;
    A() { start(); }
 
    public void run() {
    synchronized (this) {
    Random randomNumbers = new Random();
    int face;
    for (int count = 1; count <= 20; count++) {
    face = 1 + randomNumbers.nextInt(500); }
        while(true) {
            System.out.print("["+id+"] ");
            try {
                wait(face);
            } catch(InterruptedException e) { 
               System.out.print("\nThread ["+id+"] interrrupted");
               break;
            }
        }
    }
}

class ThreadsDemo {
    public static void main(String[] args) {
        ArrayList list=new ArrayList();
        for(int i=0; i<5; i++) list.add(new A());
        try {Thread.sleep(3000);
        } catch(InterruptedException e) { };
        for(int i=0; i<list.size(); i++) 
            ((A) (list.get(i))).interrupt();
        for(int i=0; i<list.size(); i++) {
        if ( (A) (list.get(i)).isAlive()) {
            System.out.println("Continue."); } }
        else {
            System.out.println("---All threads now ended---"); }
        }
    }
}

Recommended Answers

All 3 Replies

Extra } at end of line 36?
Adopt a standard for where you put your { and } and stick to it to avoid this kind of problem.

Extra } at end of line 36?
Adopt a standard for where you put your { and } and stick to it to avoid this kind of problem.

I don't get it. I mean I removed the } and it still doesn't work. I even tried the other way like remove most of these { } etc and it doesn't solve the problem.

Get yourself a code editor or IDE that will indent your code for you - that's the quickest way to spot {} errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.