Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

java 6: write two thread

Posted on 2012-04-01
1
Medium Priority
?
410 Views
Last Modified: 2012-04-01
hello all,

i would like to write a java program to create two threads. one will print even numbers and another will print odd numbers. Output should be the sequence of natural numbers. 1,2,3,4,5....

any suggestion?

thanks,

wantime
0
Comment
Question by:wantime
1 Comment
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 37792497
public class TwoThreads {

    public static void main(String[] args) {
        PrintNumb n0 = new PrintNumb(0);
          PrintNumb n1 = new PrintNumb(1);
        Thread t0 = new Thread(n0);
         Thread t1 = new Thread(n1);
        t0.start();
        try{
        Thread.currentThread().sleep(1000);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        t1.start();





    }

}


class PrintNumb implements Runnable {

    int i;
  public PrintNumb(int i){
      this.i = i;
  }

    public void run() {

        while(i< 20){
            try{
            Thread.currentThread().sleep(2000);
            System.out.print(i +",");
            i+=2;
            }catch(Exception ex){
                ex.printStackTrace();
            }

        }

    }



}

Open in new window


Output:

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This video teaches viewers about errors in exception handling.
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 …
Suggested Courses

824 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