Threads PowerPoint PPT Presentation

presentation player overlay
1 / 13
About This Presentation
Transcript and Presenter's Notes

Title: Threads


1
Threads
  • How do we mimic two computers, communicating?
  • How do many programs run at once on the same
    computer?
  • What is meant by client / server?

2
what are threads?
  • independently running programs within one Unix
    process
  • can communicate through (static) variables that
    they share
  • define the Client / Server relationship
  • used when a task needs undivided attention
  • playing mp3s
  • running a task while waiting for user input

3
how threads operate
Server
main
.start
.run()
.start
communicate?
Client
.run()
4
main typically exists in the server
Server
main
.start
.run()
.start
Communicate usually through a separate class
Client
.run()
5
timeline
Server thread
?
main
end (not exit)
?
Client thread
6
writing a client thread
  • public class ClientClass extends Thread
  • public void run()
  • while (true)
  • // stuff

7
writing a Server
  • public class ServerClass extends Thread
  • public void run()
  • while
  • // does stuff here
  • ( true )
  • // end run()
  • public static void main (String args)
  • ClientClass clientThread new ClientClass()
  • clientThread.start()
  • ServerClass serverThread new ServerClass()
  • serverThread.start()
  • // end main
  • // end class

8
your Server Class responsibility
  • main
  • start own thread
  • start all client threads
  • run forever until commanded to stop
  • System.exit(0) from this classs .run() ends all
    threads
  • actually any System.exit(0) ends all threads.
  • many ways to command - shared variables are often
    used files etc.

9
talk to each other
  • public class commClass
  • public static String ClientToServer "idle"
  • public static String ServerToClient "idle"
  • // end commClass
  • static means everyone can use the Strings
  • commClass.ClientToServer exit
  • defines a protocol

10
typical uses of thread communications
Server
e.g. web server
registration Ive started
display this page
mouse clicks new pages
Client
e.g. web page
11
some useful methods
  • Thread.sleep( milliseconds ) - suspends this
    threads activity

12
stopping a thread
  • a clean end to a threads .run( ) method ends
    that thread.
  • A .run( ) method that is in a while (true)
    loop will not end.
  • System.exit(0) from ANYWHERE ends all threads

13
Assignment 1
  • Due one week from today
  • Write a client/server program.
  • Only the server takes text input from the user
  • The server builds the entire user text input in a
    text buffer that is shared by both
  • Upon command from the user, the client prints it
    to the screen
  • Upon command from the user, the client halts
  • Upon separate command from the user, the server
    halts
  • The user communicates only with the server
  • Use submit_cse453 .java to submit your files
Write a Comment
User Comments (0)
About PowerShow.com