Java Threads and Java Beans
1. The Concepts of Thread
1.1 What is a Thread?
What exactly is a thread? The term thread is shorthand for thread of control, and a thread of control is, at its simplest, a section of code executed independently of other threads of control within a single program.
A thread is the path taken by a program for running a task. For example, when the computer executes our ordinary programs, the execution follows the path we arranged in the program, from the entry point to the exit of the program. In the program we may need to complete a series of tasks, for example, read data from a file, process the data and write the result to another file, display an image etc. No matter how many tasks to be completed (like a to-do list) we follow the arranged path or order to get them done. Even you are running the program on a powerful computer, for example, multiprocessor computer, you still run the program in the designed order, task by task. If the tasks are not strongly dependent of each other, why don’t we put tasks into two to-do lists, then let the program concurrently do the tasks in the two lists when we have, for example, two processors on a computer. Each processor executes the tasks in one list. If this is true, we say we have two threads in the program.
Of course, not each computer has more than one processors. As the modern computer is very powerful, we can split the time into small slots. On one slot, the program execute the tasks from one listl, on the other slot from the other list. In the point of the user’s view, tasks in the two lists are concurrently executed. This technique is called multitasking. Your window system uses this technique so that you can do tasks like editing files when the IE browser is downloading a large file from the Internet.
That is the core of multithreading. We arrange a program in several threads, and let the program be concurrently run on several threads (paths).
That is the core of multithreading. We arrange a program in several threads, and let the program be concurrently run on several threads (paths).
Figure 32.1 in the text shows how multiple threads are concurrently run on single processor and multiprocessor machines, respectively.
Java provides the capability which enables you to design threads for your programs.
1.2 Why Threads?
Actually threads are everywhere. Even if your program never explicitly creates a thread, the system may create threads on your behalf. For example, when your program begins an application, the Java interpreter starts a thread for the main method and a thread for JVM housekeeping tasks (garbage collection, finalization). The AWT and Swing user interface frameworks create threads for managing user interface events. They are running behind your programs concurrently.
2. Creating Tasks and Threads
2.1 Tasks
To efficiently design multithread program for your jobs, you need to identify tasks and the dependence of tasks. Tasks are about what need to be done.
In Java, tasks are considered as objects. To create tasks, you have to first declare a class for tasks. A task class must implement the Runnable interface which only has the run method. The only you need to do is to implement this method for your task class.
Here is the template for defining your own task class
public class MyTasks implements Runnable {
public MyTasks( .. ) {
//The jobs here
}
public MyTasks( .. ) {
//The jobs here
}
public void run() {
//how to do
}
}
//how to do
}
}
Then you can create a task instance by using new operator with the tasks class constructor.
2.2 Creating a Thread for a Task
A task must be executed in a thread. Think about the ordinary programs you have written so far in this way: you define classes and methods (tasks) and then use them in the main method. That is, you put your tasks in the main thread to run.
Similarly once you have created your tasks, you need to put them into a thread to run. The Thread class contains the constructors for you to create threads with tasks and many useful methods for controlling threads.
Creating a thread for a task is very simple
Creating a thread for a task is very simple
Thread mythread = new Thread(myTask);
2.3 Invoking a Thread to Execute its Task
After you define a thread for a task, you need to tell the JVM that the thread is ready to run by calling its start method
mythread.start();
The program in Listing 32.1 is a good example of using threads.
3. The Thread class
The Thread class defines several useful methods that you can use to control and manipulate threads.
You can use the isAlive() method to test if the thread is currently running or has been dead. The JVM randomly chooses the ready threads to run when the resource is available. However you can change this by setting a higher priority with the methodsetPriority(int p) to the thread you want to be run as soon as possible.
You can use the yield() method to temporarily release time for other threads and you can put a thread to sleep (don’t do work) for a while with the method sleep(long mills). You can use the join() method to force one thread to wait for another thread to finish.
Please read Section 32.4 carefully and try to understand the meaning of each method in the Thread class.
4. The Thread Synchronization
Here we look at the issue of sharing data between threads. Threads are the execution paths in a major program. The data information in the program may be shared by threads.
As an application example, let us look at the system for the automated teller machine (ATM). You can imagine that the operation of an ATM is a thread in the whole Bank system. Thus the system maintains a lot of threads at the same time. Account information shall be shared among all the threads.
There are scenarios in which it is possible two people to have access to the same account (e.g. a joint account). One day, a husband and wife both decide to empty the same account at the almost same time on two different ATMs (purely by chance). It is possible for two ATMs to confirm that the account has enough cash and dispense it to both parties, because the two users are causing two threads to access the account database at the same time.
It is called a race condition because the action of checking the account and changing the account status is not atomic. The term atomic is related to the atom, once considered the smallest possible unit of the matter, unable to be broken into separate parts. When a routine is considered atomic, it cannot be interrupted during its execution. In our ATM example, if the acts of “checking on the account” and “changing the account status (taking money)” were atomic, it would not be possible for another thread to check same account until the first thread had finished changing the account status.
The Java specification provides certain mechanisms that deal specifically with this problem. The Java language provides the synchronized keyword to force a method or a piece of code to be atomic. In our example, we can define a method which completes the checking andd changing as a synchronized one. Then we can make sure the account data is in the right status.
Read Section 32.9 again.
Except for the synchronized keyword, Java provides many other techniques to make threads safe, for example, Block queues, semaphores etc. If you are interested in the Java concurrent programming, I suggest you should read the Java document on the recent development on the concurrent framework
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html
5. The JavaBeans Components
Readings
|
What you need:
- To work with JavaBeans you need a Builder tool. I suggest you should install the NetBeans IDE to your computer. It is free and can be downloaded from http://www.netbeans.info/downloads/index.php. It can completely replace the JCreator IDE that you have been using so far.
5.1 Introduction to Beans
The official definition of a bean, as given in the JavaBeans specification, is “A bean is a reusable software component based on Sun’s JavaBeans specification that can be manipulated visually in a builder tool”.
Once you implement a bean, others can use it in a builder environment to produce GUI applications more efficiently.
5.2 What does a Bean look like?
A good example of a bean with rich behavior is CalendarBean by Kai Todter. The bean and its source code are freely available fromhttp://www.toedter.com/en/jcalendar. This bean gives users a convenient way of entering dates, simply by locating them in a calendar display. The figure below shows a demo image
The top half shows the appearance of the bean. Do you like it? If you have an application in which you want to the user input dates, would you like to present the user this visual input chart so that the user can input dates by justing clicking mouse? However you don’t want to code this chart from the scratch, do you?
Kai Todter has done everything for you. If you are going to use this component in your application, you only need to drop this bean into your application with Builder tool like the NetBeans. When you open the bean in the Builder tool, you can customer it to your specification, for example, you can set the property Locale to Australia, see the bottom half of the figure as well as other properties to specify your needs. Finally you will have this calendar in your application.
5.3 Where are Beans?
Actually NetBeans IDE provides a method for you to visually design the user interface for your application. After launching the NetBeans IDE you see the main window of the application as shown below
Here I am not going to teach how to use the NetBeans IDE to create an application (or project), but just let you know you can design GUI for your application visually with NetBeans IDE.
If you click on the + sign of Swing in the Palette you will a lot of Swing components like JLabel, JButton etc. That means you can add these components into your application visually and the NetBeans will write the appropriate for you. If you consider a bean as a special component, then using a bean in your project is just like adding a Swing component into your GUI.
You can see Kai’s JDateChooser bean has been in the Beans folder. It is simple to add a bean into NetBeans IDE for later use. Kai’s beans are packed in a jar file. I suppose you have downloaded the jcalendar-1.3.2.jar file. Now click on “Tools” and then choose the Palatte Manager, on the pop-up window choose “Add From JAR” button and specify the location of jcalendar-1.3.2.jar and following the instructions you can add the JDateChooser bean into NetBeans IDE. Then you can use it in any projects that you are going to develop.
6. Creating a Bean
Indeed Kai’s Calender beans are quite complicated. Here I am going to work through all the steps for creating a simple bean. Usually you should follow the following procedures;
- Writing code for a bean (of course you can use NetBeans to create a bean)
- Compiling the bean
- Generating a Java Archive (JAR) file
- Loading the bean into the GUI Builder of the NetBeans IDE
- Inspecting the bean's properties and events for later use
The bean we are going to create is an image icon label.
6.1 The code for the Label
import javax.swing.*;
import java.util.*;
import javax.imageio.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import java.awt.*;
import java.io.*;
public class MyBean extends JLabel {
public MyBean(){
setBorder(BorderFactory.createEtchedBorder());
try {
file = new File("icon.jpg");
setIcon(new ImageIcon(ImageIO.read(file)));
}
catch (IOException e) {
file = null;
setIcon(null);
}
}
private File file = null;
public MyBean(){
setBorder(BorderFactory.createEtchedBorder());
try {
file = new File("icon.jpg");
setIcon(new ImageIcon(ImageIO.read(file)));
}
catch (IOException e) {
file = null;
setIcon(null);
}
}
private File file = null;
}
6.2 Creating the Bean
First you can compile the file with either JCreator or NetBeans to get the class file MyBean.class
Then edit a manifest fule MyBean.mf for the bean
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: True
Java-Bean: True
Note the blank line between the manifest version and bean name.
To make the JAR file, use the command below
jar cvfm MyBean.jar MyBean.mf MyBean.class
Then you can also add other items, such as JPG files for icons to the JAR file. Then bean can be used in any application just as other beans although our bean is so simple (just a label).
No comments:
Post a Comment