Solved

Java Multithread sample

Posted on 2004-10-11
6
1,167 Views
Last Modified: 2008-02-01
I am having problems understanding the concept of thread and I been ask to write two single programs using multithread. They do not have to be difficult just a basic program that shows the main idea of multithread and not asking for my homework but I been searching and looking at many sites and still don get it. I know the fact that uses different classes and each thread run by itself a single process, that putting then together create a complete system.

This is what understood so far:

Class NewThread extends Thread
String name; // declaration of variables
Thread t;

NewThread (string threadname0
{
Name = threadname;
t = new Thread (this, name); // what it’s the purpose of having this here
system.out.println(“New Thread: “ + t);
t.start ( )
}
Public void run ( )
{
Try
{
For (int i=5; i>0; i--)
{
System.out.println (name + “:” + i);
Thread.sleep (1000);
}
            }
      }
}
}

It’s a valid code for a multithread code or its missing more stuff

Thanks
0
Comment
Question by:jsctechy
  • 3
  • 2
6 Comments
 
LVL 7

Expert Comment

by:dttri
ID: 12277394
 Dear,
  I think your program is missing something (at least it has syntax errors). Try a look at here:
http://www-106.ibm.com/developerworks/java/library/j-thread.html
and here:
http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html
  Hope this help,

  Tri
0
 
LVL 2

Expert Comment

by:gen718
ID: 12277578
t = new Thread (this, name); // what it’s the purpose of having this here

This creates a Thread object. The t.start() actually causes the new thread object to execute in the Java Virtual Machine. The VM calls the run() method of the thread object t at this point. You now have 2 threads running concurrently in the same application (your NewThread thread (original thread) and the t thread).

By running concurrently we mean, they are both scheduled to execute by the Java VM. When a thread actually executes is up to the thread scheduler of the VM. You can influence the scheduler by assigning a priority to each thread. Higher priority threads execute before lower priority threads.

Note: One problem with creating threads this way (i.e. Class NewThread extends Thread) is that java classes can only inherit from one other class. Therefore if the NewThread class needed to be derived from another class this approach (extending Thread) for creating multiple threads would not work. You would need the NewThread class to implement the interface Runnable (i.e. class NewThread extends SomeOtherClass implements Runnable).

A great source for info on Java thread programming is Paul Hyde's Java Thread Programming book.

Hope this helps :)
0
 
LVL 1

Author Comment

by:jsctechy
ID: 12287792
I still don get it the part where you ask me what i have
t = new Thread (this, name);
i though after t is define you can create an instance of it; therefore create a new variable

can i have a illustration of a simple multithread code where I'll be able to folow and understand

Thanks
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 2

Expert Comment

by:gen718
ID: 12288180
I wasn't asking a question. I was just pointing out your question in the comment of that line that I was going to answer in the next paragraph. :)

Thread t;
This line declares a Thread variable.

t = new Thread (this, name);  
This creates an instance of the class Thread (e.g. a Thread object) and assigns it to the variable t.

The thread object t does not execute as an independent thread until its "start" method is called.  The line t.start()  does that.  

The basic structure of your example is correct for your goal of a multithreaded program.
0
 
LVL 1

Author Comment

by:jsctechy
ID: 12290188
now if i eliminated that line
t = new Thread (this, name);  
the program will run still ?
0
 
LVL 2

Accepted Solution

by:
gen718 earned 250 total points
ID: 12293210
No you will get a null pointer exception since the t variable does not contain a Thread object.

Try running the following code to see that 2 threads are indeed executing. Rerun it a few times and notice that the output changes.

public class test extends Thread {
      String name; // declaration of variables

      Thread t;

      public test(String threadname) {
            name = threadname;
            t = new Thread(this, name);
            System.out.println("New Thread: " + t);
            t.start();
      }

      public void run() {
            for (int i = 5; i > 0; i--) {
                  System.out.println(name + ":" + i);
                  try {
                        Thread.sleep(1000);
                  } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            }
      }
      public static void main(String[] args) {
            test newtest = new test("programmer");
            for (int j=5; j > 0; j--) {
                  System.out.println("woke up in main thread = "+j);
                  try {
                        sleep(500);
                  } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            }
      }
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show, step by step, how to integrate R code into a R Sweave document
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now