CSL 210 Lab13 Threads
CSL 210 Lab13 Threads
BS(IT)3
Semester 03(Fall 2018)
Lab12: Threads
In this lab, the following topics will be covered:
1. Threads
2. Using threads
3. Timer application.
1. Threads
A thread can be thought as an execution path within a process. A process (i.e. a Java application)
will at least have one running thread, the thread main. Up to this point, we have been creating
single threaded java applications. However, almost all computer application are multi-threaded.
When creating more than one thread, these threads are run simultaneously, the CPU will switch
from one thread to another very quickly that programmer would have the feeling that they run in
parallel.
We will create a class Counter with one constructor that has the time to count down in seconds.
To make the class a thread, it must extend the java.lang.Thread class.
// An Example of Thread
public class Counter extends Thread
{
int time;
public Counter(int seconds) {
time = seconds;
}
public void run(){
while(time > 0){
System.out.println(Thread.currentThread().getName()+”
”+time);
try {
Thread.currentThread().sleep(1000);
time--;
}
catch(InterruptedException ex){
System.out.println("error :"+ex.getMessage());
}
}
}
}
Note:
The start() method for a thread class will invoke its run method. The “run” method for a thread
class is the place from which thread execution start.
Another way of creating a thread is by implementing the interface Runnable.
The counter example looks like
/*
* An Example of Test class
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TimedBomb extends JFrame implements Runnable
{
int time = 5;
JLabel lbl = new JLabel("Will Self-distruct In :"+time);
public TimedBomb()
{
super("Self Destruction");
setSize(300,100);
add(lbl);
setVisible(true);
Thread t = new Thread(this);
//this refer to this class, as it implements runnable
t.start();
}
public void run()
{
while(time > 0)
{
try
{
Thread.sleep(1000);
time--;
lbl.setText("Will Self-distruct In :"+time);
}
catch(InterruptedException e)
{
}
}
JOptionPane.showMessageDialog(this,"Window is
closing.. good bye!");
System.exit(0);
}
public static void main(String[]args)
{
new TimedBomb();
}
}
Project
o Your final demonstration of mini group project according to the following criteria.
CS Department, BUKC 4/4 Semester fall 2018
CSL-210: Object-Oriented Programming Lab Lab13: Threads
o Presentation (20 Marks)
Introduction
Problem statement
UML Diagram (Class diagram + relationships)
OOP Concepts (Encapsulation, Associatin, Aggregation, Inheritance,
Polymorphism, Abstraction, Interface)
Database Design ( Main Tables for data storage)
Screen Shots
o Demonstration (20 Marks)
Graphical User Interface (GUI)
Input /output with validation and verification
Database connectivity
Exception Handling
o Final Report (10 Marks)
Contains above all with test data.
Hard Copy + Code ( zip/rar Source Code and mail to [email protected])
And also submit your zip in the classroom.