10,11,12
10,11,12
package mypack;
public class MyPackageClass {
public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}
public static int addNumbers(int a, int b) {
return a + b;
}
}
Package democlass
import mypack.MyPackageClass;
public class PackageDemo {
public static void main(String[] args) {
MyPackageClass myPackageObject = new MyPackageClass();
myPackageObject.displayMessage();
int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);
}
}
OUTPUT
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
11)Write a program to illustrate creation of threads using runnable class. (start method
start each of the newly created thread. Inside the run method there is sleep() for suspend
the thread for 500 milliseconds).
class MyRunnable implements Runnable {
private volatile boolean running = true;
@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + "
is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
public void stopThread() {
running = false;
}
}
public class RunnableThreadExample {
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
}
}
OUTPUT:
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.
12)Develop a program to create a class MyThread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts after
this. It can be observed that both main thread and created child thread are executed
concurrently.
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread
interrupted.");
}
}
}
public class ThreadConcurrentExample {
public static void main(String[] args) {
MyThread myThread = new MyThread("Child Thread");
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Thread Count:
" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread
interrupted.");
}
}
}
}
OUTPUT:
main Thread Count: 1
Child Thread Count: 1
main Thread Count: 2
Child Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5