OBJECT ORIENTED PROGRAMMING LANGUAGE
|
|
|
- Gyles Benson
- 10 years ago
- Views:
Transcription
1 UNIT-6 (MULTI THREADING) Multi Threading: Java Language Classes The java.lang package contains the collection of base types (language types) that are always imported into any given compilation unit. This is where you'll find the declarations of Object (the root of the class hierarchy) and Class, plus threads, exceptions, wrappers for the primitive data types, and a variety of other fundamental classes. This picture illustrates the classes in java.lang, excluding all the exception and error classes. Note the Boolean, Character, and Number classes--these classes are "wrapper" classes for the primitive types. You use these classes in applications where the primitive types must be stored as objects. Note also the Throwable class--this is the root class for all exceptions and errors. Simply put, a thread is a program's path of execution. Most programs written today run as a single thread, causing problems when multiple events or actions need to occur at the same time. Let's say, for example, a program is not capable of drawing pictures while reading 1
2 keystrokes. The program must give its full attention to the keyboard input lacking the ability to handle more than one event at a time. The ideal solution to this problem is the seamless execution of two or more sections of a program at the same time. Threads allow us to do this. Multiprogramming is a rudimentary form of parallel processing in which several programs are run at the same time on a uniprocessor.since there is only one processor, there can be no true simultaneous execution of different programs. Instead, the operating system executes part of one program, then part of another, and so on. To the user it appears that all programs are executing at the same time. Multitasking, in an operating system, is allowing a user to perform more than one computer task (such as the operation of an application program) at a time. The operating system is able to keep track of where you are in these tasks and go from one to the other without losing information Multithreading is the ability of a program to manage its use by more than one thread at a time.dispatchable atomic units of the program are executing simultaneously. Multithreaded applications deliver their potent power by running many threads concurrently within a single program. From a logical point of view, multithreading means multiple lines of a single program can be executed at the same time, however, it is not the same as starting a program twice and saying that there are multiple lines of a program being executed at the same time. In this case, the operating system is treating the programs as two separate and distinct processes. Uses of Threads: Threads are used in designing serverside programs to handle multiple clients at a time. Threads are used in games and animations. We can reduce the idle time of processor. Performance of processor is improved. Reduces interferences between execution and user interface. The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: It is the thread from which other child threads will be spawned. Often, it must be the last thread to finish execution because it performs various shutdown actions. Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling 2
3 the method currentthread( ), which is a public static member of Thread. Its general form is shown here: static Thread currentthread( ) This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread. Let s begin by reviewing the following example: Program : Write a program to know the currently running Thread //Currently running thread class Current public static void main(string args[]) System.out.println ("This is first statement"); Thread t = Thread.currentThread (); System.out.println ("Current Thread: " + t); System.out.println ("Its name: " + t.getname ()); System.out.println ("Its priority:" + t.getpriority ()); Output: Differences between multi threading and multitasking: MULTI THREADING MULTI TASKING 1). More than one thread running 1). More than one process running simultaneously simultaneously 2). Its part of a program 2). Its a program. 3).it is a light-weight process. 3). It is a heavy-weight process. 4). Threads are divided into sub threads 4). Process is divided into threads. 5). Within the process threads are 5). Inter process communication is difficulty communicated. 6). Context switching between threads is 6). Context switching between process is cheaper. costly 7). It is controlled by Java(JVM) 7). It is controlled by operating System. 8).It is a specialized form of multi tasking 8). It is a generalized form of multi threading. 9). Example: java s automatic garbage 8). Program compilation at command collector. prompt window and preparing documentation at MS-Office. 3
4 Thread Life Cycle: Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states. At any time the thread falls into any one of the states. Fig: Thread Life Cycle The thread that was just created is in the born state. The thread remains in this state until the threads start method is called. This causes the thread to enter the ready state. The highest priority ready thread enters the running state when system assigns a processor to the thread i.e., the thread begins executing. When a running thread calls wait the thread enters into a waiting state for the particular object on which wait was called. Every thread in the waiting state for a given object becomes ready on a call to notify all by another thread associated with that object. When a sleep method is called in a running thread that thread enters into the suspended (sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A sleeping thread cannot use a processor even if one is available. A thread enters the dead state when its run () method completes (or) terminates for any reason. A dead thread is eventually be disposed of by the system. One common way for a running thread to enter the blocked state is when the thread issues an input or output request. In this case a blocked thread becomes ready when the input or output waits for completes. A blocked thread can t use a processor even if one is available. 4
5 Creating Threads: We know that in every java program, there is a main thread available already. Apart from this main thread, we can also create our owen threads in a program. The following steps should be used. Write a class that extends Thread class or implements Runnable interface this is available in lang package. Class Myclass extends Thread (or) Class Myclass implements Runnable Write public void run () method in that class. This is the method by default executed by any thread. Public void run() Statements; Create an object to my class, so that the run() method is available for execution. Myclass obj=new Myclass(); Create a thread and attach it to the object. Thread t=new Thread(obj); or To create a Thread, we can use the following forms: Thread t1 = new Thread (); Thread t2 = new Thread (obj); Thread t3 = new Thread (obj, "thread-name"); Start running the threads. t.start(); Syntactical code for creating and running the thread: Class Myclass extends Thread (or) Class Myclass implements Runnable Public void run() Statements; Class Demo Public static void main(string args[])throws InterruptedException Myclass obj=new Myclass(); Thread t=new Thread(obj); t.start(); 5
6 Thread Class Methods: To know the currently running thread: Thread t = Thread.currentThread (); To start a thread: t.start (); To stop execution of a thread for a specific time: Thread.sleep (milliseconds); To get the name of the thread: String name = t.getname (); To set the new name to the thread: t.setname ("New Name"); To get the priority of the thread: int priority = t.getpriority(); To set the priority of the thread: t.setpriority (int priority); Thread priorities can change from 1 to 10. We can also use the following constants to represent priorities: Thread.MAX_PRIORITY value is 10 Thread.MIN_PRIORITY value is 1 Thread.NORM_PRIORITY value is 5 To test if a thread is still alive: t.isalive () returns true/false To wait till a thread dies: t.join (); To send a notification to a waiting thread: obj.notify (); To send notification to all waiting threads: obj.notifyall (); To wait till the obj is released (till notification is sent): obj.wait (); 6
7 Program : Write a program to create and run a Thread. //creating and running a Thread class MyThread extends Thread public void run () for (int i = 0;i<100;i++) System.out.print (i + "\t"); class TDemo public static void main(string args[]) MyThread obj = new MyThread (); Thread t = new Thread (obj); t.start (); Output: As a result, the numbers will be displayed starting from 1 to 99 using a for loop. If u want to terminate the program in the middle, u can press Ctrl+C from the keyboard. This leads to abnormal program termination. It means the entire program is terminated, not just the thread. If we want to terminate only the thread that is running the code inside run() method, we should devise our own mechanism.if we press Ctrl+C, we are abnormally terminating the program. This is dangerous. Abnormal program termination may cause loss of data and lead to unreliable results. So,we should terminate the thread only, not the program.hown can we terminate the thread smoothly is the question now. Terminating the thread: A thread will terminate automatically when it comes out of run() method. To terminate the thread on our own logic. For the following steps can be used 1.Create the Boolean type variable and initialize it to false. Boolean stop=false; 3.Let us assume that we want to terminate the thread when the user presses <Enter> key. So, when the user presses that button, make the Boolean type variable as true. 7
8 Stop=true; 3.Check this variable in run() method and when it is true, make the thread return from the run() method. Public void run() If(stop==true) return; Program to showing how to terminate the thread by pressing the enter button import java.io.*; class MyThread implements Runnable boolean stop=false; public void run () for (int i = 0;i<=100000;i++) System.out.print (i + "\t"); if(stop==true) return; //come out of run class TDemo public static void main(string args[]) throws IOException MyThread obj = new MyThread (); Thread t = new Thread (obj); t.start ();//stop the thread when enter key is pressed System.in.read(); obj.stop=true; Output: Press <Enter> to stop the thread at any time. What is the difference between extends thread and implements Runnable? which one is advantageous? extends thread and implements Runnable -both are functionally same. But when we write extends Thread, there is no scope toextend another class, as multiple inheritance is not supported in java. Class MyClass extends Thread,AnotherClass //invalid If we write implements Runnable, then still there is scope to extend another class. Class MyClass extends AnotherClass implements Runnable //valid This is definitely advantageous when the programmer wants to use threads and also wants to access the features of another class. 8
9 Single tasking using a thread: A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be executed. We can create a thread and pass the 3 tasks one by one to the thread. For this purpose, we can write all these tasks separately in separate methods; task1(), task2(), task3(). Then these methods should be called from run() method, one by one. Remember, a thread executes only the code inside the run() method. It can never execute other methods unless they are called from run(). Note: public void run() method is executed by the thread by default. //single tasking using a thread class MyThread implements Runnable public void run() //executes tasks one by one by calling the methods. task1(); task2(); task3(); void task1() System.out.println("this is task1"); void task2() System.out.println("this is task2"); void task3() System.out.println("this is task3"); class Sin public static void main(string args[]) MyThread obj=new MyThread(); Thread t1=new Thread(obj); t1.start(); Output: java Sin This is task1() This is task2() This is task3() In this program, a single thread t1 is used to execute three tasks. 9
10 Multi Tasking Using Threads: In multi taskin, several tasks are executed at a time. For this purpose, we need more than one thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks. Then those tasks are simultaneously executed by the two threads. Using more than one thread is called multi threading. Program : Write a program to create more than one thread. //using more than one thread is called Multi Threading class Theatre extends Thread String str; Theatre (String str) this.str = str; public void run() for (int i = 1; i <= 10 ; i++) System.out.println (str + " : " + i); try Thread.sleep (2000); catch (InterruptedException ie) ie.printstacktrace (); class TDemo1 public static void main(string args[]) Theatre obj1 = new Theatre ("Cut Ticket"); Theatre obj2 = new Theatre ("Show Chair"); Thread t1 = new Thread (obj1); Thread t2 = new Thread (obj2); t1.start (); t2.start (); Output: In the preceding example, we have used 2 threads on the 2 objects of TDemo1 class. First we have taken a String variable str in Theatre class. Then we passed two strings- cut ticket and show chair into that variable from TDemo1 class. When t1. start () is executed, it starts execution run () method code showing cut ticket. Note that in run () method, we used: 10
11 Thread. sleep (2000) is a static method in Thread class, which is used to suspend execution of a thread for some specified milliseconds. Since this method can throw InterruptedException, we caught it in catch block. When Thread t1 is suspended immediately t2. start () will make the thread t2 to execute and when it encounters Thread.sleep(2000), it will suspend for specified time meanwhile t1 will get executed respectively. In this manner, both the threads are simultaneously executed.synchronizing threads, daemon threads, thread groups. Multiple Threads Acting on Single Object: First letus see why 2 threads shouldshare same object(samerun()method). We write an object to represent one task. If there is a different task,we take another object. When two people (threads) want to perform same task then they need same object (run () method) to be executed each time. Take the case of railway reservation. Every day several people want reservation of a berth for them. The procedure to reserve the berth is same for all the people. So we need some object with same run () method to be executed repeatedly for all the people (threads). Let us think that only one berth is available in a train and two passengers (threads) are asking for that berth in two different counters. The clerks at different counters sent a request to the server to allot that berth to their passengers. Let us see now to whom that berth is allotted. Program : Write a program to create multiple threads and make the threads to act on single object. //Thread unsafe Two threads acting on same object. class Reserve implements Runnable //available berths are 1 int available = 1; int wanted; //accept wanted berths at runtime Reserve (int i) wanted = i; public void run() //display available berths System.out.println ("Number of berths available: " + available); //if available berths more thanwanted betrhs if ( available >= wanted) //get the name of the passenger String name = Thread.currentThread ().getname (); System.out.println (wanted + " berths alloted to: " + name); try Thread.sleep (2000); // wait for priniting the ticket available = available - wanted; //update the no.of available berths catch (InterruptedException ie) ie.printstacktrace (); 11
12 else System.out.println ("Sorry, no berths available"); class UnSafe public static void main(string args[]) Reserve obj = new Reserve (1); Thread t1 =new Thread (obj); Thread t2 = new Thread (obj); t1.setname ("First Person"); t2.setname ("Second Person"); t1.start (); t2.start (); Output: java UnSafe Number of berths available:1 1 berth is allotted to First person Number of berths available:1 1 berth is allotted to Second person Please observe the output in the preceding program. It is absurd. It has allotted the same berth to both the passengers. Since both the threads are acting on the same object simultaneously, then the result is unreliable. What is the solution for this problem? Ans: Thread Synchronization Synchronizing Threads or Thread Synchronization or Thread Safe: When a thread is acting on an object preventing other threads from acting on the same object is called Thread Synchronization or Thread Safe. The object on which the threads are synchronized is called synchronized object. The Object on which the Threads are synchronized is called synchronized object or Mutex (Mutually Exclusive Lock).Synchronized object is like a locked object, locked on a thread. It is like a room with only one door. A person has entered the room and locked form it from behind. The second person who wants to enter the room should wait till the first person comes out. In this way, a thread also locks the object after entering it. Then the next thread cannot enter it till the first thread comes out. This means the object is locked mutually on threads. So, this object is called mutex. Thread synchronization is done in two ways: Using synchronized block we can synchronize a block of statements. e.g.: synchronized (obj) statements; 12
13 Here, object represents the object to be locked or synchronized. The statements inside the synchronized block are all available to only one thread at a time. They are not available to more than one thread simultaneously. To synchronize an entire method code we can use synchronized word before method name e.g.: synchronized void method () Stmts; Now the statements inside the method are not available to more than one thread at a time. This method code is synchronized. Write a program to thread synchronization by using synchronized block. //Thread synchronization- Two threads acting on same object //Multiple Threads acting on single object class Reserve implements Runnable int available = 1; int wanted; Reserve (int i) wanted = i; public void run() synchronized (this) System.out.println ("Number of berths available: " + available); if ( available >= wanted) String name = Thread.currentThread ().getname (); System.out.println (wanted + " berths alloted to: " + name); try Thread.sleep (2000); // wait for priniting the ticket available = available - wanted; catch (InterruptedException ie) ie.printstacktrace (); else System.out.println ("Sorry, no berths available"); class Safe public static void main(string args[]) Reserve obj = new Reserve (1); Thread t1 =new Thread (obj); Thread t2 = new Thread (obj); t1.setname ("First Person"); t2.setname ("Second Person"); 13
14 t1.start (); t2.start (); Output: Write a program to thread synchronization by using synchronized keyword before the method name /** Write a Java program that creates three threads. First thread displays Good Morning every one second, the second thread displays Hello every two seconds and the third thread displays Welcome every threeseconds. */ class A extends Thread synchronized public void run() try while(true) sleep(10); System.out.println("good morning"); catch(exception e) class B extends Thread synchronized public void run() try while(true) sleep(20); 14
15 System.out.println("hello"); catch(exception e) class C extends Thread synchronized public void run() try while(true) sleep(30); System.out.println("welcome"); catch(exception e) class ThreadDemo public static void main(string args[]) A t1=new A(); B t2=new B(); C t3=new C(); t1.start(); t2.start(); t3.start(); Output: Press Cntrl+C to exit Good morning Hello Good morning Welcome Good morning Hello Good morning Good morning Hello 15
16 InterThread Communication: Thread Communication: In some cases two or more threads should communicate with each other. One thread output may be send as input to other thread. For example, a consumer thread is waiting for a Producer to produce the data (or some goods). When the Producer thread completes production of data, then the Consumer thread should take that data and use it. In producer class we take a StringBuffer object to store data, in this case; we take some numbers from 1 to 5. These numbers are added to StringBuffer object. Until producer completes placing the data into StringBuffer the consumer has to wait. Producer sends a notification immediately after the data production is over. /** Write a Java program that correctly implements producer consumer problem using the concept of interthread communication.*/ //java program for producer and consumer--inter thread communication class Producer implements Runnable Thread1 t; Producer(Thread1 t) this.t=t; new Thread(this,"Producer").start(); public void run() int i=0; while (true) t.put(i++); class Consumer implements Runnable Thread1 t; Consumer(Thread1 t) this.t=t; new Thread(this,"Consumer").start(); public void run() int i=0; while (true) t.get(); 16
17 class ProducerConsumer public static void main(string[] args) Thread1 t=new Thread1(); System.out.println("Press Control+c to exit"); new Producer(t); new Consumer(t); Output: Press Control+C to exit Put:0 Get:0 Put:1 Get1. Deamon Threads: Daemon threads are sometimes called "service" threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. This thread, provided by the JVM, will scan programs for variables that will never be accessed again and free up their resources back to the system. A thread can set the daemon flag by passing a true boolean value to the setdaemon() method. If a false boolean value is passed, the thread will become a user thread. However, this must occur before the thread has been started. A deamon thread is a thread that executes continuously. Daemon threads are service providers for other threads or objects. It generally provides a background processing. To make a thread t as a deamon thread, we can use setdeamon() method as: t.setdeamon(true); To know if a thread is deamon or not, isdeamon is useful. boolean x=t.isdaemon(). Write a example program for setting a thread as a daemon thread public class DaemonDemo extends Thread public void run() for(int i=0;i<5;i++) System.out.println(this.getName()+" :"+i); public static void main(string args[]) DaemonDemo d1=new DaemonDemo(); DaemonDemo d2=new DaemonDemo(); 17
18 d1.setname("daemon thread"); d2.setname("normal thread"); d1.setdaemon(true); d1.setpriority(thread.min_priority); d1.start(); d2.start(); Output: Daemon thread:0 Normal thread:0. Daemon thread:4 Normal thread:4 Thread Groups: Thread Group: A ThreadGroup represents a group of threads. The main advantage of taking several threads as a group is that by using a single method, we will be able to control all the threads in the group. Thread groups offer a convenient way to manage groups of threads as a unit. This is particularly valuable in situations in which you want to suspend and resume a number of related threads. For example, imagine a program in which one set of threads is used for printing a document, another set is used to display the document on the screen, and another set saves the document to a disk file. If printing is aborted, you will want an easy way to stop all threads related to printing. Thread groups offer this convenience. Creating a thread group: ThreadGroup tg = new ThreadGroup ( groupname ); To add a thread to this group (tg):thread t1 = new Thread (tg, targetobj, threadname ); To add another thread group to this group (tg): ThreadGroup tg1 = new ThreadGroup (tg, groupname ); To know the parent of a thread: tg.getparent (); To know the parent thread group: t.getthreadgroup (); This returns a ThreadGroup object to which the thread t belongs. To know the number of threads actively running in a thread group: t.activecount (); To change the maximum priority of a thread group tg: tg.setmaxpriority (); 18
19 Program : Write a program to demonstrate the creation of thread group. //Using ThreadGroup import java.io.*; class WhyTGroups public static void main (String args[]) throws IOException Reservation res = new Reservation (); Cancellation can = new Cancellation (); //Create a ThreadGroup ThreadGroup tg = new ThreadGroup ("Reservation Group"); //Create 2 threads and add them to thread group Thread t1 = new Thread (tg, res, "First Thread"); Thread t2 = new Thread (tg, res, "Second Thread"); //Create another thread group as a child to tg ThreadGroup tg1 = new ThreadGroup (tg, "Cancellation Group"); Thread t3 = new Thread (tg1, can, "Third Thread"); Thread t4 = new Thread (tg1, can, "Fourth Thread"); //find parent group of tg1 System.out.println ("Parent of tg1 = " + tg1.getparent ()); //set maximum priority tg1.setmaxpriority (7); 19
20 System.out.println ("Thread group of t1 = " + t1.getthreadgroup ()); System.out.println ("Thread group of t3 = " + t3.getthreadgroup ()); t1.start (); t2.start (); t3.start (); t4.start (); System.out.println ("Number of threads in this group : " + tg.activecount () ); class Reservation extends Thread public void run () System.out.println ("I am Reservation Thread"); class Cancellation extends Thread public void run () System.out.println ("I am Cancellation Thread"); Output: 20
JAVA - MULTITHREADING
JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amulti threaded programming language which means we can develop multi threaded program
Introduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
Threads 1. When writing games you need to do more than one thing at once.
Threads 1 Threads Slide 1 When writing games you need to do more than one thing at once. Threads offer a way of automatically allowing more than one thing to happen at the same time. Java has threads as
Multithreaded Programming
Java Multithreaded Programming This chapter presents multithreading, which is one of the core features supported by Java. The chapter introduces the need for expressing concurrency to support simultaneous
CS11 Java. Fall 2014-2015 Lecture 7
CS11 Java Fall 2014-2015 Lecture 7 Today s Topics! All about Java Threads! Some Lab 7 tips Java Threading Recap! A program can use multiple threads to do several things at once " A thread can have local
File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The
Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language
Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description
Fundamentals of Java Programming
Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui
Threads & Tasks: Executor Framework
Threads & Tasks: Executor Framework Introduction & Motivation WebServer Executor Framework Callable and Future 12 April 2012 1 Threads & Tasks Motivations for using threads Actor-based Goal: Create an
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
Crash Course in Java
Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is
Building a Multi-Threaded Web Server
Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous
An Overview of Java. overview-1
An Overview of Java overview-1 Contents What is Java Major Java features Java virtual machine Java programming language Java class libraries (API) GUI Support in Java Networking and Threads in Java overview-2
Java Memory Model: Content
Java Memory Model: Content Memory Models Double Checked Locking Problem Java Memory Model: Happens Before Relation Volatile: in depth 16 March 2012 1 Java Memory Model JMM specifies guarantees given by
Outline of this lecture G52CON: Concepts of Concurrency
Outline of this lecture G52CON: Concepts of Concurrency Lecture 10 Synchronisation in Java Natasha Alechina School of Computer Science [email protected] mutual exclusion in Java condition synchronisation
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.
Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 Name: SOLUTIONS Athena* User Name: Instructions This quiz is 50 minutes long. It contains
Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
JAVA Program For Processing SMS Messages
JAVA Program For Processing SMS Messages Krishna Akkulu The paper describes the Java program implemented for the MultiModem GPRS wireless modem. The MultiModem offers standards-based quad-band GSM/GPRS
1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius
Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1
Creating a Simple, Multithreaded Chat System with Java
Creating a Simple, Multithreaded Chat System with Java Introduction by George Crawford III In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The program will demonstrate
www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk
CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling
Introduction to Java. CS 3: Computer Programming in Java
Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods
Homework/Program #5 Solutions
Homework/Program #5 Solutions Problem #1 (20 points) Using the standard Java Scanner class. Look at http://natch3z.blogspot.com/2008/11/read-text-file-using-javautilscanner.html as an exampleof using the
Chapter 2 Introduction to Java programming
Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break
Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75
Preet raj Core Java and Databases CS4PR Time Allotted: 3 Hours Final Exam: Total Possible Points 75 Q1. What is difference between overloading and overriding? 10 points a) In overloading, there is a relationship
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
Chapter 6, The Operating System Machine Level
Chapter 6, The Operating System Machine Level 6.1 Virtual Memory 6.2 Virtual I/O Instructions 6.3 Virtual Instructions For Parallel Processing 6.4 Example Operating Systems 6.5 Summary Virtual Memory General
Using Files as Input/Output in Java 5.0 Applications
Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead
Java Coding Practices for Improved Application Performance
1 Java Coding Practices for Improved Application Performance Lloyd Hagemo Senior Director Application Infrastructure Management Group Candle Corporation In the beginning, Java became the language of the
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C
Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in
Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.
Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input
Tutorial: Getting Started
9 Tutorial: Getting Started INFRASTRUCTURE A MAKEFILE PLAIN HELLO WORLD APERIODIC HELLO WORLD PERIODIC HELLO WORLD WATCH THOSE REAL-TIME PRIORITIES THEY ARE SERIOUS SUMMARY Getting started with a new platform
Monitors, Java, Threads and Processes
Monitors, Java, Threads and Processes 185 An object-oriented view of shared memory A semaphore can be seen as a shared object accessible through two methods: wait and signal. The idea behind the concept
CS 121 Intro to Programming:Java - Lecture 11 Announcements
CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take
Java Crash Course Part I
Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe [email protected] Overview (Short) introduction to the environment Linux
Explain the relationship between a class and an object. Which is general and which is specific?
A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third
agileworkflow Manual 1. agileworkflow 2. The repository 1 of 29 Contents Definition
agileworkflow Manual Contents 1. Intro 2. Repository 3. Diagrams 4. Agents 4.1. Dispatcher Service 4.2. Event Service 4.3. Execution Service 5. Variables 6. Instances 7. Events 7.1. External 7.2. File
Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis
Built-in Concurrency Primitives in Java Programming Language by Yourii Martiak and Mahir Atmis Overview One of the many strengths of Java is the built into the programming language support for concurrency
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program
Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman
Network/Socket Programming in Java. Rajkumar Buyya
Network/Socket Programming in Java Rajkumar Buyya Elements of C-S Computing a client, a server, and network Client Request Result Network Server Client machine Server machine java.net Used to manage: URL
I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015
RESEARCH ARTICLE An Exception Monitoring Using Java Jyoti Kumari, Sanjula Singh, Ankur Saxena Amity University Sector 125 Noida Uttar Pradesh India OPEN ACCESS ABSTRACT Many programmers do not check for
Concurrent programming in Java
Concurrent programming in Java INF4140 04.10.12 Lecture 5 0 Book: Andrews - ch.05 (5.4) Book: Magee & Kramer ch.04 - ch.07 INF4140 (04.10.12) Concurrent programming in Java Lecture 5 1 / 33 Outline 1 Monitors:
Konzepte objektorientierter Programmierung
Konzepte objektorientierter Programmierung Prof. Dr. Peter Müller Werner Dietl Software Component Technology Exercises 3: Some More OO Languages Wintersemester 04/05 Agenda for Today 2 Homework Finish
Chapter 8 Implementing FSP Models in Java
Chapter 8 Implementing FSP Models in Java 1 8.1.1: The Carpark Model A controller is required for a carpark, which only permits cars to enter when the carpark is not full and does not permit cars to leave
Java Programming Fundamentals
Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few
Java CPD (I) Frans Coenen Department of Computer Science
Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials
LAB4 Making Classes and Objects
LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to
public static void main(string[] args) { System.out.println("hello, world"); } }
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
Web Development in Java
Web Development in Java Detailed Course Brochure @All Rights Reserved. Techcanvass, 265, Powai Plaza, Hiranandani Garden, Powai, Mumbai www.techcanvass.com Tel: +91 22 40155175 Mob: 773 877 3108 P a g
Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.
Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
Java Concurrency Framework. Sidartha Gracias
Java Concurrency Framework Sidartha Gracias Executive Summary This is a beginners introduction to the java concurrency framework Some familiarity with concurrent programs is assumed However the presentation
Capabilities of a Java Test Execution Framework by Erick Griffin
Capabilities of a Java Test Execution Framework by Erick Griffin Here we discuss key properties and capabilities of a Java Test Execution Framework for writing and executing discrete Java tests for testing
Lecture J - Exceptions
Lecture J - Exceptions Slide 1 of 107. Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.
WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25
Part I. Multiple Choice Questions (2 points each):
Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******
13 File Output and Input
SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to
Thread Synchronization and the Java Monitor
Articles News Weblogs Buzz Chapters Forums Table of Contents Order the Book Print Email Screen Friendly Version Previous Next Chapter 20 of Inside the Java Virtual Machine Thread Synchronization by Bill
Manual. Programmer's Guide for Java API
2013-02-01 1 (15) Programmer's Guide for Java API Description This document describes how to develop Content Gateway services with Java API. TS1209243890 1.0 Company information TeliaSonera Finland Oyj
Operating Systems Concepts: Chapter 7: Scheduling Strategies
Operating Systems Concepts: Chapter 7: Scheduling Strategies Olav Beckmann Huxley 449 http://www.doc.ic.ac.uk/~ob3 Acknowledgements: There are lots. See end of Chapter 1. Home Page for the course: http://www.doc.ic.ac.uk/~ob3/teaching/operatingsystemsconcepts/
java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner
java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources
Java from a C perspective. Plan
Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,
The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0
The following applies to all exams: Once exam vouchers are purchased you have up to one year from the date of purchase to use it. Each voucher is valid for one exam and may only be used at an Authorized
WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.
Java Packages KNOWLEDGE GOALS Understand what a package does. Organizes large collections of Java classes Provides access control for variables and methods using the modifier 'protected' Helps manage large
Sample CSE8A midterm Multiple Choice (circle one)
Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names
Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013
Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper
Mutual Exclusion using Monitors
Mutual Exclusion using Monitors Some programming languages, such as Concurrent Pascal, Modula-2 and Java provide mutual exclusion facilities called monitors. They are similar to modules in languages that
Java Programming Language
Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Subclasses and
Object-Oriented Programming in Java
CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio
Amazon Glacier. Developer Guide API Version 2012-06-01
Amazon Glacier Developer Guide Amazon Glacier: Developer Guide Copyright 2016 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in
1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders
1.00 Lecture 1 Course Overview Introduction to Java Reading for next time: Big Java: 1.1-1.7 Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders
How to create/avoid memory leak in Java and.net? Venkat Subramaniam [email protected] http://www.durasoftcorp.com
How to create/avoid memory leak in Java and.net? Venkat Subramaniam [email protected] http://www.durasoftcorp.com Abstract Java and.net provide run time environment for managed code, and Automatic
Informatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1
The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose
Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1
Exception Handling Error handling in general Java's exception handling mechanism The catch-or-specify priciple Checked and unchecked exceptions Exceptions impact/usage Overloaded methods Interfaces Inheritance
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
Division of Informatics, University of Edinburgh
CS1Bh Lecture Note 20 Client/server computing A modern computing environment consists of not just one computer, but several. When designing such an arrangement of computers it might at first seem that
Operating Systems 4 th Class
Operating Systems 4 th Class Lecture 1 Operating Systems Operating systems are essential part of any computer system. Therefore, a course in operating systems is an essential part of any computer science
Web Development and Core Java Lab Manual V th Semester
Web Development and Core Java Lab Manual V th Semester DEPT. OF COMPUTER SCIENCE AND ENGINEERING Prepared By: Kuldeep Yadav Assistant Professor, Department of Computer Science and Engineering, RPS College
System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :
Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class
A Comparison of the Concurrency and Real-Time Features of Ada 95 and Java
A Comparison of the Concurrency and Real-Time Features of Ada 95 and Java Benjamin M. Brosgol Ada Core Technologies 79 Tobey Road Belmont, MA 02478 USA +1.617.489.4027 (Phone) +1.617.489.4009 (FAX) [email protected]
Java Application Developer Certificate Program Competencies
Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement
CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit
Chapter 1 Java Program Design and Development
presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented
java Features Version April 19, 2013 by Thorsten Kracht
java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................
AP Computer Science Java Subset
APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall
