0% found this document useful (0 votes)
2 views4 pages

Java Multithreading Example Code

The document defines two Java classes - A and B - that extend the Thread class and implement the run() method to print values. The main method creates instances of A and B, starts both threads, and prints their output intermixed rather than in order due to thread scheduling. In the second example, A and B implement Runnable and are passed to Thread constructors to demonstrate an alternative threading approach.

Uploaded by

jaitun godhani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Java Multithreading Example Code

The document defines two Java classes - A and B - that extend the Thread class and implement the run() method to print values. The main method creates instances of A and B, starts both threads, and prints their output intermixed rather than in order due to thread scheduling. In the second example, A and B implement Runnable and are passed to Thread constructors to demonstrate an alternative threading approach.

Uploaded by

jaitun godhani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

*;

class A extends Thread

public void run()

for(int i=0;i<10;i++)

[Link]("A"+i);

class B extends Thread

public void run()

for(int i=0;i<10;i++)

[Link]("B"+i);

public class HelloWorld{


public static void main(String []args)

A U=new A();

B g=new B();

[Link]();

[Link]();

Output:

A0
B0
B1
B2
B3
A1
A2
A3
A4
A5
A6
A7
A8
A9
B4
B5
B6
B7
B8
B9

Second try:

import [Link].*;
class A implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
[Link]("A"+i);
}

}
}

class B implements Runnable


{
public void run()
{
for(int i=0;i<10;i++)
{
[Link]("B"+i);
}
}
}
public class HelloWorld{

public static void main(String []args)


{
Thread U=new Thread(new A());
Thread g=new Thread(new B());
[Link]();
[Link]();

}
}

Output:
A0
A1
A2
A3
A4
A5
A6
A7
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
A8
A9

You might also like