Solved

java 6: write two thread

Posted on 2012-04-01
1
402 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 500 total points
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

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…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

771 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