Solved

Java Multithread sample

Posted on 2004-10-11
6
1,166 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
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…

744 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

14 Experts available now in Live!

Get 1:1 Help Now