You are on page 1of 37

2: Java thread

CS508
Robert Zhu
Setting up your Workspace

 Workspace is where your projects and


programs are stored.
 Usually some directory in the file system
 The workspace is set when Eclipse starts
 In this course, for instance, we may set the
work space to
 /home/usrname/course/cs112b1

 All code will be saved in this directory


 Demo

2.2
Some important concepts about Eclipse
Environment
 Workbench
 Perspective
 Views
 Editor
 …

2.3
Workbench

 The term Workbench refers to the desktop


development environment
 The Workbench aims to achieve seamless
tool integration and controlled openness by
providing a common paradigm for the
creation, management, and navigation of
workspace resources.

2.4
Understanding Perspective
 Each Workbench window contains one or more perspectives

 Each perspective provides a set of functionality aimed at


accomplishing a specific type of task or works with specific types of
resources.

 For example, the Java perspective combines views that you would
commonly use while editing Java source files, while the C/C++
perspective contains the views that you would use for editing C++
files

 You might need switch perspectives frequently.

2.5
Built-in Eclipse Perspectives
 Resource
 Arrange your files and projects.
 Java
 Develop programs in the Java language.
 Debug
 Diagnose and debug problems that occur at runtime.
 Java Browsing
 Java Type Hierarchy
 Plug-in Development
 CVS Repository Exploring
 Team Synchronizing

2.6
Views

 Views support editors and provide alternative


presentations as well as ways to navigate the
information in your Workbench. 

 For example, the Navigator and other navigation


views display projects and other resources that
you are working with.

2.7
Editors

 Most perspectives in the Workbench are


comprised of an editor area and one or
more views
 You can associate different editors with
different types of files.
 Any number of editors can be open at
once, but only one can be active at a time.

2.8
Creating Java Projects

 Demo: Creating a project in the workspace

2.9
Creating Java Packages

 A Package in Java is a group of classes which are


often closely or logically related in some way
 Package corresponds to the directory hierarchy in
the file system.
 course.cs112b1.assignment1
 Organizing source files into different packages is a
good programming style.
 Demo: creating a package

2.10
Adding Java Classes

 Class is the basic compilation unit in Java.

 Demo: Creating class

2.11
Import existing files
 Some files are given and you want to import them
to your projects rather than creating them again

 Demo: Importing other files of assignment1 to the


project

 You can also copy-and-paste files to your project


folder
 Refresh the file view if you don’t see them

2.12
Running the code

 Currently, no implementation is provided in the


given files. You are expected to fill the
implementation details.

 We need a class which has a main() method as


the entrance for execution

 Demo: Adding the main() method and run the


program

2.13
Other issues

 Demo:
 Removing files from the project
 Check (or not) “Build Automatically”
 Window->Preferences
 Project->Properties
 …
 Eclipse provides a very good Help system
 “Help->Help Contents” for more information

2.14
Threads

2.15
Problem

 Multiple tasks for computer


 Draw & display images on screen
 Check keyboard & mouse input
 Send & receive data on network
 Read & write files to disk
 Perform useful computation (editor, browser, game)
 How does computer do everything at once?
 Multitasking
 Multiprocessing

2.16
Multitasking (Time-Sharing)

 Approach
 Computer does some work on a task
 Computer then quickly switch to next task
 Tasks managed by operating system
(scheduler)
 Computer seems to work on tasks
concurrently
 Can improve performance by reducing
waiting

2.17
Multitasking Can Aid Performance
 Single task

 Two tasks

2.18
Multiprocessing (Multithreading)

 Approach
 Multiple processing units (multiprocessor)
 Computer works on several tasks in parallel
 Performance can be improved

Dual-core AMD 32 processor 4096 processor


Athlon X2 Pentium Xeon Cray X1

2.19
Perform Multiple Tasks Using…

1. Process
 Definition – executable program loaded in
memory
 Has own address space
 Variables & data structures (in memory)
 Each process may execute a different program
 Communicate via operating system, files,
network
 May contain multiple threads

2.20
Perform Multiple Tasks Using…

2. Thread
 Definition – sequentially executed stream of
instructions
 Shares address space with other threads
 Has own execution context
 Program counter, call stack (local variables)
 Communicate via shared access to data
 Multiple threads in process execute same
program
 Also known as “lightweight process”

2.21
Motivation for Multithreading

1. Captures logical structure of problem


 May have concurrent interacting components
 Can handle each component using separate
thread
 Simplifies programming for problem
 Example

Web Server uses Multiple simultaneous


threads to handle … web browser requests
2.22
Motivation for Multithreading

2. Better utilize hardware resources


 When a thread is delayed, compute other
threads
 Given extra hardware, compute threads in
parallel
 Reduce overall execution time
 Example

Multiple simultaneous Handled faster by


web browser requests… multiple web servers
2.23
Multithreading Overview

 Motivation & background


 Threads
 Creating Java threads
 Thread states
 Scheduling
 Synchronization
 Data races
 Locks
 Wait / Notify

2.24
Programming with Threads
 Concurrent programming
 Writing programs divided into independent tasks
 Tasks may be executed in parallel on multiprocessors
 Multithreading
 Executing program with multiple threads in parallel
 Special form of multiprocessing

2.25
Creating Threads in Java

 Two approaches
 Thread class
public class Thread extends Object { … }
 Runnable interface
public interface Runnable {
public void run(); // work  thread
}

2.26
Thread Class

public class Thread extends Object


implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable R); // Thread 
R.run()
public Thread(Runnable R, String name);

public void run(); // if no R, work for thread


public void start(); // begin thread execution
...
}

2.27
More Thread Class Methods

public class Thread extends Object {



public static Thread currentThread()
public String getName()
public void interrupt()
public boolean isAlive()
public void join()
public void setDaemon()
public void setName()
public void setPriority()
public static void sleep()
public static void yield()
}

2.28
Creating Threads in Java

1. Thread class
 Extend Thread class and override the run method
 Example
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT T = new MyT () ; // create thread
T.start(); // begin running thread
… // thread executing in parallel

2.29
Creating Threads in Java

2. Runnable interface
 Create object implementing Runnable interface
 Pass it to Thread object via Thread constructor
 Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread T = new Thread(new MyT); // create thread
T.start(); // begin running thread
… // thread executing in parallel
2.30
Creating Threads in Java

 Note
 Thread starts executing only if start() is called

 Runnable is interface
 So it can be multiply inherited
 Required for multithreading in applets

2.31
Threads – Thread States
 Java thread can be in one of these states
 New – thread allocated & waiting for start()
 Runnable – thread can begin execution
 Running – thread currently executing
 Blocked – thread waiting for event (I/O, etc.)
 Dead – thread finished
 Transitions between states caused by
 Invoking methods in class Thread
 new(), start(), yield(), sleep(), wait(), notify()…
 Other (external) events
 Scheduler, I/O, returning from run()…

2.32
Threads – Thread States

 State diagram

new start
notify, notifyAll,
new runnable
IO complete,
sleep expired,
yield,
scheduler join complete
time
slice
running blocked
IO, sleep,
terminate wait, join

dead

2.33
Daemon Threads

 Java threads types


 User
 Daemon
 Provide general services
 Typically never terminate
 Call setDaemon() before start()
 Program termination
1. All user threads finish
2. Daemon threads are terminated by JVM
3. Main program finishes

2.34
Threads – Scheduling

 Scheduler
 Determines which runnable threads to run
 Can be based on thread priority
 Part of OS or Java Virtual Machine (JVM)
 Scheduling policy
 Nonpreemptive (cooperative) scheduling
 Preemptive scheduling

2.35
Threads – Non-preemptive Scheduling

 Threads continue execution until


 Thread terminates
 Executes instruction causing wait (e.g., IO)
 Thread volunteering to stop (invoking yield or
sleep)

2.36
Threads – Preemptive Scheduling

 Threads continue execution until


 Same reasons as non-preemptive scheduling
 Preempted by scheduler

2.37

You might also like