This document provides an overview of threads in Java. It defines a thread as a program's path of execution that allows multiple parts of a program to run concurrently. The document discusses two ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. It also covers how to start, stop, suspend and resume threads. Creating threads allows programs to handle multiple events simultaneously rather than having to give full attention to just one event at a time.
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
Java allows multithreading which means multiple tasks can run concurrently within a single program. A thread goes through different states in its lifecycle from being born to running to termination. Threads can be created by implementing the Runnable interface and overriding the run method. The run method contains the task being performed by the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
The document discusses object oriented programming concepts including applets, differences between applets and applications, the lifecycle of an applet, creating applets, passing parameters to applets, an introduction to Swing components and limitations of AWT. It also discusses the MVC architecture and its components - model, view and controller.
An applet is a Java program that runs in a web browser. It is embedded in an HTML page and runs in the Java Virtual Machine (JVM). To create an applet, a class must extend the Applet class. The applet lifecycle includes initialization, starting, painting, stopping, and destruction. Applets allow Java programs to be run from web pages and have graphical user interfaces.
This document provides an overview of multithreading and thread synchronization in Java. It discusses that multithreading allows executing multiple threads simultaneously and threads are lightweight subprocesses that share a common memory area. It then covers thread life cycle states, advantages of multithreading, synchronization techniques like synchronized methods and blocks, and inter-thread communication methods like wait(), notify(), and notifyAll().
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
The document discusses various concepts related to multithreading in Java including thread-safe collections, executors, and synchronizers. It provides details on blocking queues, concurrent hash maps, executors that allow submitting tasks to thread pools, and synchronizers like cyclic barriers, countdown latches, and semaphores that help manage groups of threads. It also discusses how to update Swing components safely from multiple threads using EventQueue methods like invokeLater().
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
The document discusses multithreading and threading concepts in Java. It defines a thread as a single sequential flow of execution within a program. Multithreading allows executing multiple threads simultaneously by sharing the resources of a process. The key benefits of multithreading include proper utilization of resources, decreased maintenance costs, and improved performance of complex applications. Threads have various states like new, runnable, running, blocked, and dead during their lifecycle. The document also explains different threading methods like start(), run(), sleep(), yield(), join(), wait(), notify() etc and synchronization techniques in multithreading.
Java allows multithreading which means multiple tasks can run concurrently within a single program. A thread goes through different states in its lifecycle from being born to running to termination. Threads can be created by implementing the Runnable interface and overriding the run method. The run method contains the task being performed by the thread. Synchronization is needed when multiple threads access shared resources to prevent race conditions and ensure only one thread accesses the resource at a time.
The document discusses object oriented programming concepts including applets, differences between applets and applications, the lifecycle of an applet, creating applets, passing parameters to applets, an introduction to Swing components and limitations of AWT. It also discusses the MVC architecture and its components - model, view and controller.
An applet is a Java program that runs in a web browser. It is embedded in an HTML page and runs in the Java Virtual Machine (JVM). To create an applet, a class must extend the Applet class. The applet lifecycle includes initialization, starting, painting, stopping, and destruction. Applets allow Java programs to be run from web pages and have graphical user interfaces.
This document provides an overview of multithreading and thread synchronization in Java. It discusses that multithreading allows executing multiple threads simultaneously and threads are lightweight subprocesses that share a common memory area. It then covers thread life cycle states, advantages of multithreading, synchronization techniques like synchronized methods and blocks, and inter-thread communication methods like wait(), notify(), and notifyAll().
This document discusses inter-thread communication methods like wait() and notify() that allow threads to synchronize access to shared resources. It describes the producer-consumer problem that can occur when threads access a shared buffer without synchronization. It provides examples of incorrect and correct implementations of the producer-consumer pattern using wait(), notify(), and synchronization to allow a producer thread to add items to a buffer while a consumer thread removes items.
The document discusses various concepts related to multithreading in Java including thread-safe collections, executors, and synchronizers. It provides details on blocking queues, concurrent hash maps, executors that allow submitting tasks to thread pools, and synchronizers like cyclic barriers, countdown latches, and semaphores that help manage groups of threads. It also discusses how to update Swing components safely from multiple threads using EventQueue methods like invokeLater().
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
This document discusses synchronization in multi-threaded programs. It covers monitors, which are used as mutually exclusive locks to synchronize access to shared resources. The synchronized keyword in Java can be used in two ways - by prefixing it to a method header, or by synchronizing an object within a synchronized statement. Examples are provided to demonstrate synchronization issues without locking, and how to resolve them by using the synchronized keyword in methods or on objects.
This document discusses C# threads and threading concepts in 3 paragraphs:
C# threads are managed by the System.Threading.Thread class and are passed a function using a ThreadStart delegate. Threads can be started and have properties like IsBackground that indicate their state.
When threads share resources, synchronization is needed to serialize access. The C# lock statement can be used to synchronize access to shared resources like queues. Other synchronization primitives like Monitor, Interlocked, and ReaderWriterLock are also available.
User interface threads in Windows Forms are separate from worker threads that do background processing. Worker threads must communicate with UI threads using Form methods like Invoke, BeginInvoke, and EndInvoke
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
This document discusses various Java concepts like object-oriented programming, compilation, the main method signature, command line arguments, byte code checking, type casting, and input/output in Java using classes like DataInputStream and Scanner. It provides code examples for accepting user input using these classes and parsing the input into different data types like integer and float. It also compares DataInputStream and Scanner, noting that Scanner avoids the need to manually convert input types.
Inter thread communication & runnable interfacekeval_thummar
Inter-thread communication allows threads to pause execution in critical sections and allow other threads to enter those sections. It uses the wait(), notify(), and notifyAll() methods of the Object class. wait() pauses a thread until another calls notify() or notifyAll(), notify() wakes one waiting thread, and notifyAll() wakes all waiting threads. The Runnable interface provides a common protocol for objects to execute code while active. To create a thread using Runnable, a class implements Runnable and defines a run() method, a Thread object is created passing the Runnable, and start() is called to execute run().
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This document discusses multithreading in C#. It introduces threads and multithreading, describing how operating systems allow multitasking and how threads work. It explains that the .NET Framework supports multithreading using the System.Threading namespace and Thread class. It describes properties and methods of the Thread class, potential problems like deadlocks that can occur with multithreading, and solutions like synchronization and locking to prevent issues.
The document provides an overview of object oriented programming and network programming concepts. It discusses topics like IP addresses, ports, sockets, client-server programming, and the java.net and java.util packages. The java.net package contains classes for network programming in Java like Socket, ServerSocket, URL, and InetAddress. The java.util package contains general-purpose utility classes like ArrayList, HashMap, Properties and Date.
- Python allows programmers to write multi-threaded programs using its threading module. This allows running multiple threads concurrently to perform asynchronous tasks or operations in parallel.
- The threading module provides Thread class which represents a thread of execution. New threads can be created by subclassing Thread and overriding its run method. start() method launches the execution of the thread.
- Synchronization between threads is important to prevent race conditions. The threading module provides Lock objects to synchronize access to shared resources.
This document describes a unit project on threading and Java threading. It explains concepts like semaphores, test-and-set operations, reentrancy, and preemption. It also reviews two sample Java classes, Msynch and Msynch1, that demonstrate multithreading concepts. Msynch is described as functioning properly while Msynch1 contains three synchronization errors that would prevent proper execution.
Carol McDonald gave a presentation on Java concurrency utilities introduced in J2SE 5.0. She discussed motivation for improved concurrency tools, common concurrency issues, and key utilities like Executor framework, locks, synchronizers, and concurrent collections. The utilities make concurrent programming easier and improve performance of multithreaded Java applications.
This document provides a summary of threads in Python. It begins by defining what a thread is and how it allows for multitasking by time-division multiplexing the processor between threads. It then discusses how to start new threads in Python using the thread and threading modules, including examples. It also covers how to create threads that subclass the Thread class and how to synchronize threads using locks.
- Python allows programmers to write multithreaded programs that run multiple threads concurrently for more efficient use of resources and responsiveness.
- The main benefits of multithreading over multiple processes are that threads within a process can share data and resources more easily. Threads also have less memory overhead than processes.
- There are two main modules for multithreading in Python - the older thread module and the newer threading module, which provides more powerful features and methods for managing threads.
- The document is a lab manual for an introductory Java programming course that provides instructions on installing Java, using an IDE, and writing simple Java programs.
- It explains how to create a "Hello World" Java program using BlueJ or JCreator IDEs, compile and run the program, and addresses common errors students may encounter.
- The document provides an example "Hello World" Java program and explains the key components of a basic Java class including the class definition, main method, and use of System.out.println to display output.
Presentation derived from the "What's new in Python 2.5" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
The document discusses multithreading concepts like concurrency and threading, how to create and control threads including setting priorities and states, and how to safely share resources between threads using synchronization, locks, and wait/notify methods to avoid issues like deadlocks. It also covers deprecated thread methods and increased threading support in JDK 1.5.
Don't be fooled by the thumbnail - the first couple of slides are a silly joke I forgot to remove before uploading.
Presentation derived from the "What's new in Python 2.4" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
This document summarizes key features introduced in Java SE 5.0 (Tiger) including generics, autoboxing/unboxing, enhanced for loops, type-safe enums, varargs, static imports, and annotations. It also discusses performance enhancements in the virtual machine as well as new concurrency utilities like Executors and ScheduledExecutorService that make multi-threaded programming easier and more robust.
The document discusses concurrency programming in Java. It covers the scope of concurrency including multi-threading, multi-core, and distributed systems. It then discusses key aspects of concurrency programming like shared data/coordination for correctness and performance. It provides examples of thread-safety issues and how to address them using locks, volatile fields, and final fields to safely publish objects between threads.
Threads allow programs to perform multiple tasks concurrently. A thread is a single sequence of execution within a program. Multithreading refers to multiple threads running within a single program. Threads share program resources but have their own call stack and local variables. Threads are created by extending the Thread class or implementing the Runnable interface. Synchronization is needed when multiple threads access shared resources concurrently to prevent race conditions. The wait() and notify() methods enable threads to cooperate by pausing and resuming execution.
Thread is the basic unit of CPU utilization in an operating system. A single-threaded process can only perform one task at a time, while a multithreaded process can perform multiple tasks simultaneously using threads. Java uses the Thread class and Runnable interface to create and manage threads. The main thread is created automatically, while additional threads can be instantiated by implementing Runnable or extending Thread. Synchronization is needed when threads share resources to prevent race conditions.
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
The document discusses Java performance and threading. It provides an overview of performance concepts, the performance process, and measurement techniques like benchmarking and profiling. It also covers key threading concepts like thread states, synchronization, and how to share data across threads using synchronized methods, objects, and wait/notify.
This document discusses synchronization in multi-threaded programs. It covers monitors, which are used as mutually exclusive locks to synchronize access to shared resources. The synchronized keyword in Java can be used in two ways - by prefixing it to a method header, or by synchronizing an object within a synchronized statement. Examples are provided to demonstrate synchronization issues without locking, and how to resolve them by using the synchronized keyword in methods or on objects.
This document discusses C# threads and threading concepts in 3 paragraphs:
C# threads are managed by the System.Threading.Thread class and are passed a function using a ThreadStart delegate. Threads can be started and have properties like IsBackground that indicate their state.
When threads share resources, synchronization is needed to serialize access. The C# lock statement can be used to synchronize access to shared resources like queues. Other synchronization primitives like Monitor, Interlocked, and ReaderWriterLock are also available.
User interface threads in Windows Forms are separate from worker threads that do background processing. Worker threads must communicate with UI threads using Form methods like Invoke, BeginInvoke, and EndInvoke
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
This document discusses various Java concepts like object-oriented programming, compilation, the main method signature, command line arguments, byte code checking, type casting, and input/output in Java using classes like DataInputStream and Scanner. It provides code examples for accepting user input using these classes and parsing the input into different data types like integer and float. It also compares DataInputStream and Scanner, noting that Scanner avoids the need to manually convert input types.
Inter thread communication & runnable interfacekeval_thummar
Inter-thread communication allows threads to pause execution in critical sections and allow other threads to enter those sections. It uses the wait(), notify(), and notifyAll() methods of the Object class. wait() pauses a thread until another calls notify() or notifyAll(), notify() wakes one waiting thread, and notifyAll() wakes all waiting threads. The Runnable interface provides a common protocol for objects to execute code while active. To create a thread using Runnable, a class implements Runnable and defines a run() method, a Thread object is created passing the Runnable, and start() is called to execute run().
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This document discusses multithreading in C#. It introduces threads and multithreading, describing how operating systems allow multitasking and how threads work. It explains that the .NET Framework supports multithreading using the System.Threading namespace and Thread class. It describes properties and methods of the Thread class, potential problems like deadlocks that can occur with multithreading, and solutions like synchronization and locking to prevent issues.
The document provides an overview of object oriented programming and network programming concepts. It discusses topics like IP addresses, ports, sockets, client-server programming, and the java.net and java.util packages. The java.net package contains classes for network programming in Java like Socket, ServerSocket, URL, and InetAddress. The java.util package contains general-purpose utility classes like ArrayList, HashMap, Properties and Date.
- Python allows programmers to write multi-threaded programs using its threading module. This allows running multiple threads concurrently to perform asynchronous tasks or operations in parallel.
- The threading module provides Thread class which represents a thread of execution. New threads can be created by subclassing Thread and overriding its run method. start() method launches the execution of the thread.
- Synchronization between threads is important to prevent race conditions. The threading module provides Lock objects to synchronize access to shared resources.
This document describes a unit project on threading and Java threading. It explains concepts like semaphores, test-and-set operations, reentrancy, and preemption. It also reviews two sample Java classes, Msynch and Msynch1, that demonstrate multithreading concepts. Msynch is described as functioning properly while Msynch1 contains three synchronization errors that would prevent proper execution.
Carol McDonald gave a presentation on Java concurrency utilities introduced in J2SE 5.0. She discussed motivation for improved concurrency tools, common concurrency issues, and key utilities like Executor framework, locks, synchronizers, and concurrent collections. The utilities make concurrent programming easier and improve performance of multithreaded Java applications.
This document provides a summary of threads in Python. It begins by defining what a thread is and how it allows for multitasking by time-division multiplexing the processor between threads. It then discusses how to start new threads in Python using the thread and threading modules, including examples. It also covers how to create threads that subclass the Thread class and how to synchronize threads using locks.
- Python allows programmers to write multithreaded programs that run multiple threads concurrently for more efficient use of resources and responsiveness.
- The main benefits of multithreading over multiple processes are that threads within a process can share data and resources more easily. Threads also have less memory overhead than processes.
- There are two main modules for multithreading in Python - the older thread module and the newer threading module, which provides more powerful features and methods for managing threads.
- The document is a lab manual for an introductory Java programming course that provides instructions on installing Java, using an IDE, and writing simple Java programs.
- It explains how to create a "Hello World" Java program using BlueJ or JCreator IDEs, compile and run the program, and addresses common errors students may encounter.
- The document provides an example "Hello World" Java program and explains the key components of a basic Java class including the class definition, main method, and use of System.out.println to display output.
Presentation derived from the "What's new in Python 2.5" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
The document discusses multithreading concepts like concurrency and threading, how to create and control threads including setting priorities and states, and how to safely share resources between threads using synchronization, locks, and wait/notify methods to avoid issues like deadlocks. It also covers deprecated thread methods and increased threading support in JDK 1.5.
Don't be fooled by the thumbnail - the first couple of slides are a silly joke I forgot to remove before uploading.
Presentation derived from the "What's new in Python 2.4" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
This document summarizes key features introduced in Java SE 5.0 (Tiger) including generics, autoboxing/unboxing, enhanced for loops, type-safe enums, varargs, static imports, and annotations. It also discusses performance enhancements in the virtual machine as well as new concurrency utilities like Executors and ScheduledExecutorService that make multi-threaded programming easier and more robust.
The document discusses concurrency programming in Java. It covers the scope of concurrency including multi-threading, multi-core, and distributed systems. It then discusses key aspects of concurrency programming like shared data/coordination for correctness and performance. It provides examples of thread-safety issues and how to address them using locks, volatile fields, and final fields to safely publish objects between threads.
Threads allow programs to perform multiple tasks concurrently. A thread is a single sequence of execution within a program. Multithreading refers to multiple threads running within a single program. Threads share program resources but have their own call stack and local variables. Threads are created by extending the Thread class or implementing the Runnable interface. Synchronization is needed when multiple threads access shared resources concurrently to prevent race conditions. The wait() and notify() methods enable threads to cooperate by pausing and resuming execution.
Thread is the basic unit of CPU utilization in an operating system. A single-threaded process can only perform one task at a time, while a multithreaded process can perform multiple tasks simultaneously using threads. Java uses the Thread class and Runnable interface to create and manage threads. The main thread is created automatically, while additional threads can be instantiated by implementing Runnable or extending Thread. Synchronization is needed when threads share resources to prevent race conditions.
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
The document discusses Java performance and threading. It provides an overview of performance concepts, the performance process, and measurement techniques like benchmarking and profiling. It also covers key threading concepts like thread states, synchronization, and how to share data across threads using synchronized methods, objects, and wait/notify.
Thread is an independent path of execution through program code. The JVM gives each thread its own method-call stack to track execution. When multiple threads execute byte-code instruction sequences in the same program concurrently, it is known as multithreading. Java accomplishes multithreading through its Thread class, with each Thread object describing a single thread of execution that occurs in its run() method.
The document discusses threads and multithreading in Java. It defines a thread as a flow of execution with a beginning, execution sequence, and end. Multithreading allows multiple threads to run simultaneously within a single program. It describes how to create threads by extending the Thread class or implementing Runnable. The document also discusses thread states, priorities, synchronization, and race conditions that can occur when multiple threads access shared data.
This document discusses string handling in Java. It covers string methods like charAt(), concat(), contains(), endsWith(), equals(), length(), replace(), split(), toLowerCase(), toUpperCase(), and trim(). It also discusses immutable nature of strings in Java and special operations like concatenation using + operator. The document provides examples to explain the usage of each string method.
The document discusses multithreading concepts in Java, including:
- Multithreading allows multiple tasks in a program to run concurrently by using threads. Threads are lightweight sub-processes that can run tasks independently and in parallel.
- There are two main ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. The run() method specifies the task to be performed by the thread.
- Thread states include new, ready, running, blocked, and terminated. Thread methods like start(), join(), sleep(), yield(), interrupt() control thread execution and synchronization.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
Multithreading allows programs to have multiple threads that can run concurrently. Each thread defines a separate path of execution. Processes are programs that are executing, while threads exist within a process and share its resources. Creating a new thread requires fewer resources than creating a new process. There are two main ways to define a thread - by implementing the Runnable interface or by extending the Thread class.
Multithreading allows a program to split into multiple subprograms called threads that can run concurrently. Threads go through various states like new, runnable, running, blocked, and dead. There are two main ways to create threads: by extending the Thread class or implementing the Runnable interface. Threads can have different priorities that influence scheduling order. Multithreading allows performing multiple operations simultaneously to save time without blocking the user, and exceptions in one thread do not affect others.
The document discusses threads and multithreading in Java. It defines a thread as a single sequential flow of control that runs within the address space of a process. It notes that threads allow programs to accomplish multiple simultaneous tasks. The document then covers thread states, priorities, synchronization, and provides examples of a producer-consumer problem implemented with and without synchronization.
Multithreading and concurrency in androidRakesh Jha
Here you will learn -
What is Multithreading
What is concurrency
Process Vs Thread
Improvements and issues with concurrency
Limits of concurrency gains
Concurrency issues
Threads pools with the Executor Framework
AsyncTask and the UI Thread
Code
This document discusses multithreading in Java. It begins by explaining the difference between single-threaded and multithreaded programs. A multithreaded program contains two or more threads that can run concurrently. Each thread defines a separate path of execution. The document then covers key aspects of multithreading like creating threads by extending the Thread class or implementing the Runnable interface, starting and controlling threads, thread priorities, synchronization, and inter-thread communication.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help boost feelings of calmness, happiness and focus.
This document provides information on multithreading, networking, and other Java concepts. It discusses how to create threads in Java by extending the Thread class or implementing Runnable, and describes methods like sleep(), wait(), notify() etc. It also covers networking topics like sockets, servers, clients and protocols. Examples of socket programming and a chatting program using sockets are included. Finally, it discusses classes like URL, URLConnection and HttpURLConnection for working with URLs.
This document provides an overview of multi-threaded programming in Java. It discusses how to create threads that extend the Thread class or implement the Runnable interface. It describes how asynchronous thread execution can lead to unpredictable ordering. It also covers issues like data races that can occur from concurrent reads and writes to shared memory by multiple threads. The document introduces thread synchronization using locks to avoid data races and provides an example of deadlock that can occur from incorrect lock usage.
This document discusses multithreading, generators, and decorators in Python. It begins by explaining multithreading and how it allows performing multiple tasks simultaneously through processes and threads. It then provides details on threads in Python, including how to create and use threads. Next, it covers generators in Python by explaining iterators, generator functions, and generator objects. It provides examples of creating generators using both generator functions and generator expressions. Finally, it briefly introduces decorators in Python but does not provide any details.
This document outlines a project to measure the performance of multithreaded Java programs on different systems. It discusses benchmarking three workloads - calculating trapezoidal rule, sorting arrays, and computing Fibonacci numbers - using different numbers of threads. Performance is measured on Intel Core 2 Duo and Intel Centrino Duo systems running Windows Vista and Ubuntu. The results show that for CPU-intensive tasks, using the optimal number of threads can improve performance, but adding excessive threads harms performance due to overhead. Multithreading is most effective for I/O-bound tasks.
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESsuthi
Short Notes on OOP
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). A feature of objects is an object's procedures that can access and often modify the data fields of the object with which they are associated (objects have a notion of "this" or "self"). In OOP, computer programs are designed by making them out of objects that interact with one another. OOP languages are diverse, but the most popular ones are class-based, meaning that objects are instances of classes, which also determine their types.
Apostila de como fazer e usar certas técnicas de criptografia utilizando dos preceitos e teorias mais conhecidos no mercado. Vários capítulos descrevem e demonstrar como fazer toda a parte criptográfica desde os simples métodos até os mais complicados. Não cobre tudo, mas ajudo muito.
O documento fornece um guia rápido sobre o que é o Dropbox e como usá-lo. O Dropbox permite armazenar e acessar arquivos de qualquer dispositivo de forma sincronizada através da nuvem. Os usuários podem adicionar arquivos arrastando-os para a pasta do Dropbox e compartilhar arquivos e pastas com outros através de links.
Este documento discute a instalação e distribuição de energia para residências, abordando a potência total instalada e a divisão da carga por circuitos para itens como iluminação, chuveiros, tomadas e motores.
This document describes 3Dxp, an API created by the Interactive Audio Special Interest Group to extend Microsoft's DirectSound 3.0 API and enable 3D audio hardware acceleration. 3Dxp provides a standardized way for software developers to pass 3D audio positioning parameters to third-party hardware and software solutions in a way that is compatible with DirectSound3D. The document outlines how 3Dxp works, the parameters it supports, guidelines for game/application developers, and a reference code implementation to detect and interface with 3Dxp compliant audio drivers.
O documento fornece uma receita de Pastel de Belém, um doce tradicional português, com instruções detalhadas para a massa e recheio. A massa é feita com farinha, manteiga e gema e o recheio é um creme de leite, gemas e açúcar com baunilha e casca de limão. Os pasteis são assados até ficarem secos.
This document contains recipes for several Middle Eastern dishes including:
1) Shish Tawook, a chicken dish marinated in a tomato, chili, garlic and yogurt sauce then grilled.
2) Kofta Yaidez, ground lamb meatballs baked with chicken, mushrooms, cheese and white sauce.
3) Arabian Rice, a rice pilaf with mutton, onion, cinnamon, and pine nuts.
4) Several dessert recipes including Aish Al Saraya, a rosewater bread pudding, and Namorra, a coconut milk pudding baked with eggs and semolina.
5) Sheik El Mehshi, stuffed eggplant baked with a
La pandemia de COVID-19 ha tenido un impacto significativo en la economía mundial. Muchos países experimentaron fuertes caídas en el PIB y aumentos en el desempleo debido a los cierres generalizados y las restricciones a los viajes. Aunque las vacunas han permitido la reapertura de muchas economías, los efectos a largo plazo de la pandemia en sectores como el turismo y los viajes aún no están claros.
This document provides an introduction to stored procedures in MySQL. It begins with a definition of stored procedures as subprograms stored in a database that can contain SQL statements. The document then discusses why stored procedures are useful, including that they are fast, portable, reusable components that centralize logic in the database. It also covers how to set up MySQL for stored procedures and demonstrates starting the mysql client.
This document provides a tutorial for creating organic 3D ribbon effects in Flash CS3 or later using ActionScript 3.0. It explains how to generate stunning, colorful ribbon patterns that react to user interaction. The tutorial walks through setting up variables and classes to define ribbon particles and their properties. Methods are described for moving the particles to create flowing ribbons, calculating virtual points around each particle, and drawing ribbon segments between points. Adjusting various parameters allows generating different ribbon effects that could be used for visualizations or animations. The full source code is provided to experiment with and modify to create custom ribbon animations.
This tutorial explains how to create a simple particle system in Flash using ActionScript 3. Key steps include:
1. Creating a symbol to represent individual particles and exporting it for ActionScript.
2. Defining a Particle class with properties like position, velocity, and a constructor to initialize new particles.
3. Installing an ENTER_FRAME listener to call an update method each frame, incrementing the particle's position.
4. Adding random velocity, looping through an array of particles to update them, and removing old particles to maintain a constant number. With just a few lines of code, complex particle effects can be achieved.
The document discusses personal pronouns, demonstrative pronouns, interrogative pronouns, relative pronouns, reciprocal pronouns, reflexive pronouns, indefinite pronouns, and noun cases in Finnish. Personal pronouns refer to people and decline based on person and number. There are also different types of plural forms in Finnish including nominative plural, partitive plural, and inflected plural which is formed with an infix.
Este documento contém formulários e informações sobre o processo de admissão em programas de pós-graduação de uma universidade. Inclui solicitação de inscrição, lista de documentos necessários, normas de inscrição e pagamento. Também inclui formulários para solicitação de bolsa de estudos e autorização de débito em cartão de crédito.
This document provides instructions for connecting to a MySQL database from a Java application using JSP (JavaServer Pages) under Windows and Tomcat web server. It includes steps for installing Java, Tomcat, and the MySQL connector JAR file. It also covers setting up environmental variables and starting/stopping the Tomcat server. The code examples show how to test the MySQL driver, establish a database connection, and execute queries to retrieve data from the database.
This document is a collection of Indian recipes compiled by Somesh Rao. It contains over 100 recipes for breads, snacks, vegetables, lentils, rice, fish, chicken, lamb and desserts. The recipes were collected from various sources over the internet and aim to provide graduate students with access to authentic Indian cooking. The document includes introductions from Somesh Rao and Sanjiv Singh discussing the compilation of the recipes and acknowledging other contributors. It also includes a guide to common Indian ingredients.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive function. Exercise causes chemical changes in the brain that may help protect against mental illness and improve symptoms for those who already suffer from conditions like depression and anxiety.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
20 Comprehensive Checklist of Designing and Developing a WebsitePixlogix Infotech
Dive into the world of Website Designing and Developing with Pixlogix! Looking to create a stunning online presence? Look no further! Our comprehensive checklist covers everything you need to know to craft a website that stands out. From user-friendly design to seamless functionality, we've got you covered. Don't miss out on this invaluable resource! Check out our checklist now at Pixlogix and start your journey towards a captivating online presence today.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Building RAG with self-deployed Milvus vector database and Snowpark Container...Zilliz
This talk will give hands-on advice on building RAG applications with an open-source Milvus database deployed as a docker container. We will also introduce the integration of Milvus with Snowpark Container Services.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
4759826-Java-Thread
1. Introduction to Java threads
A quick tutorial on how to implement threads in Java
By Donald G. Drake, JavaWorld.com, 04/01/96
This article describes how threads are implemented in the Java programming language.
Before exploring the details of Java, a general overview of threads is needed.
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 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
allows us to do this.
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. Under Unix, forking a process creates a
child process with a different address space for both code and data. However, fork()
creates a lot of overhead for the operating system, making it a very CPU-intensive
operation. By starting a thread instead, an efficient path of execution is created while still
sharing the original data area from the parent. The idea of sharing the data area is very
beneficial, but brings up some areas of concern that we'll discuss later.
Creating threads
Java's creators have graciously designed two ways of creating threads: implementing an
interface and extending a class. Extending a class is the way Java inherits methods and
variables from a parent class. In this case, one can only extend or inherit from a single
parent class. This limitation within Java can be overcome by implementing interfaces,
which is the most common way to create threads. (Note that the act of inheriting merely
allows the class to be run as a thread. It is up to the class to start() execution, etc.)
Interfaces provide a way for programmers to lay the groundwork of a class. They are
used to design the requirements for a set of classes to implement. The interface sets
everything up, and the class or classes that implement the interface do all the work. The
different set of classes that implement the interface have to follow the same rules.
There are a few differences between a class and an interface. First, an interface can only
contain abstract methods and/or static final variables (constants). Classes, on the other
2. hand, can implement methods and contain variables that are not constants. Second, an
interface cannot implement any methods. A class that implements an interface must
implement all methods defined in that interface. An interface has the ability to extend
from other interfaces, and (unlike classes) can extend from multiple interfaces.
Furthermore, an interface cannot be instantiated with the new operator; for example,
Runnable a=new Runnable(); is not allowed.
The first method of creating a thread is to simply extend from the Thread class. Do this
only if the class you need executed as a thread does not ever need to be extended from
another class. The Thread class is defined in the package java.lang, which needs to be
imported so that our classes are aware of its definition.
import java.lang.*;
public class Counter extends Thread
{
public void run()
{
....
}
}
The above example creates a new class Counter that extends the Thread class and
overrides the Thread.run() method for its own implementation. The run() method is
where all the work of the Counter class thread is done. The same class can be created by
implementing Runnable:
import java.lang.*;
public class Counter implements Runnable
{
Thread T;
public void run()
{
....
}
}
Here, the abstract run() method is defined in the Runnable interface and is being
implemented. Note that we have an instance of the Thread class as a variable of the
Counter class. The only difference between the two methods is that by implementing
Runnable, there is greater flexibility in the creation of the class Counter. In the above
example, the opportunity still exists to extend the Counter class, if needed. The majority
of classes created that need to be run as a thread will implement Runnable since they
probably are extending some other functionality from another class.
Do not think that the Runnable interface is doing any real work when the thread is being
executed. It is merely a class created to give an idea on the design of the Thread class. In
3. fact, it is very small containing only one abstract method. Here is the definition of the
Runnable interface directly from the Java source:
package java.lang;
public interface Runnable {
public abstract void run();
}
That is all there is to the Runnable interface. An interface only provides a design upon
which classes should be implemented. In the case of the Runnable interface, it forces the
definition of only the run() method. Therefore, most of the work is done in the Thread
class. A closer look at a section in the definition of the Thread class will give an idea of
what is really going on:
public class Thread implements Runnable {
...
public void run() {
if (target != null) {
target.run();
}
}
...
}
From the above code snippet it is evident that the Thread class also implements the
Runnable interface. Thread.run() checks to make sure that the target class (the class that
is going to be run as a thread) is not equal to null, and then executes the run() method of
the target. When this happens, the run() method of the target will be running as its own
thread.
Starting and stopping
Since the different ways to create an instance of a thread are now apparent, we will
discuss the implementation of threads beginning with the ways available to start and stop
them using a small applet containing a thread to illustrate the mechanics:
import java.applet.*;
import java.awt.*;
public class CounterThread extends Applet implements Runnable
{
Thread t;
int Count;
public void init()
{
Count=0;
t=new Thread(this);
t.start();
4. }
public boolean mouseDown(Event e,int x, int y)
{
t.stop();
return true;
}
public void run()
{
while(true)
{
Count++;
repaint();
try {
t.sleep(10);
} catch (InterruptedException e) {}
}
}
public void paint(Graphics g)
{
g.drawString(Integer.toString(Count),10,10);
System.out.println("Count= "+Count);
}
public void stop()
{
t.stop();
}
}
The above applet will start counting from 0 displaying its output to both the screen and
the console. A quick glance might give the impression that the program will start
counting and display every number, but this is not the case. A closer examination of the
execution of this applet will reveal its true identity.
In this case, the CounterThread class was forced to implement Runnable since it
extended the class Applet. As in all applets, the init() method gets executed first. In
init(), the variable Count is initialized to zero and a new instance of the Thread class is
created. By passing this to the Thread constructor, the new thread will know which
object to run. In this case this is a reference to CounterThread. After the thread is
created it needs to be started. The call to start() will call the target's run() method,
which is CounterThread.run(). The call to start() will return right away and the
thread will start executing at the same time. Note that the run() method is an infinite
loop. It is infinite because once the run() method exits, the thread stops executing. The
run() method will increment the variable Count, sleep for 10 milliseconds and send a
request to refresh the applet's display.
Note that it is important to sleep somewhere in a thread. If not, the thread will consume
all CPU time for the process and will not allow any other methods such as threads to be
5. executed. Another way to cease the execution of a thread is to call the stop() method. In
this example, the thread stops when the mouse is pressed while the cursor is in the applet.
Depending on the speed of the computer the applet runs on, not every number will be
displayed, because the incrementing is done independent of the painting of the applet.
The applet can not be refreshed at every request, so the OS will queue the requests and
successive refresh requests will be satisfied with one refresh. While the refreshes are
queuing up, the Count is still being incremented but not displayed.
Suspending and resuming
Once a thread is stopped, it cannot be restarted with the start() command, since stop()
will terminate the execution of a thread. Instead you can pause the execution of a thread
with the sleep() method. The thread will sleep for a certain period of time and then
begin executing when the time limit is reached. But, this is not ideal if the thread needs to
be started when a certain event occurs. In this case, the suspend() method allows a
thread to temporarily cease executing and the resume() method allows the suspended
thread to start again. The following applet shows the above example modified to suspend
and resume the applet.
public class CounterThread2 extends Applet implements Runnable
{
Thread t;
int Count;
boolean suspended;
public boolean mouseDown(Event e,int x, int y)
{
if(suspended)
t.resume();
else
t.suspend();
suspended = !suspended;
return true;
}
...
}
import java.applet.*;
import java.awt.*;
public class CounterThread2 extends Applet implements Runnable
{
Thread t;
int Count;
boolean suspended;
public void init()
{
Count=0;
suspended=false;
t=new Thread(this);
t.start();
}
6. public boolean mouseDown(Event e,int x, int y)
{
if(suspended)
t.resume();
else
t.suspend();
suspended = !suspended;
return true;
}
public void run()
{
while(true)
{
Count++;
repaint();
try {
t.sleep(10);
} catch (InterruptedException e) {}
}
}
public void paint(Graphics g)
{
g.drawString(Integer.toString(Count),10,10);
System.out.println("Count= "+Count);
}
public void stop()
{
t.stop();
}
}
To keep track of the current state of the applet, the boolean variable suspended is used.
Distinguishing the different states of an applet is important because some methods will
throw exceptions if they are called while in the wrong state. For example, if the applet
has been started and stopped, executing the start() method will throw an
IllegalThreadStateException exception.
Scheduling
Java has a Thread Scheduler that monitors all running threads in all programs and decides
which threads should be running and which are in line to be executed. There are two
characteristics of a thread that the scheduler identifies in its decision process. One, the
most important, is the priority of the thread, the other is the daemon flag. The scheduler's
basic rule is if there are only daemon threads running, the Java Virtual Machine (JVM)
will exit. New threads inherit the priority and daemon flag from the thread that created it.
The scheduler determines which thread should be executed by analyzing the priorities of
7. all threads. Those with the highest priority are allowed execution before any lower
priority threads.
The scheduler can be of two flavors, preemptive or non-preemptive. Preemptive
schedulers give a certain time-slice to all threads running on the system. The scheduler
decides which thread is next to run and resume() that thread for some constant period of
time. When the thread has executed for that time period it will be suspended() and the
next thread scheduled will be resumed(). Non-preemptive schedulers decide which
thread should run and run it until the thread is complete. The thread has full control of the
system for as long as it likes. The yield() method is a way for a thread to force the
scheduler to start executing another waiting thread. Depending on the system Java is
running on, the scheduler can be either preemptive or non-preemptive.
Priorities
The scheduler determines which thread should be running based on a priority number
assigned to each thread. The range of priorities is from 1 to 10. The default priority of a
thread is Thread.NORM_PRIORITY, which is assigned the value of 5. Two other static
variables are made available, they are Thread.MIN_PRIORITY, which is set to 1, and
Thread.MAX_PRIORITY, which is set to 10. The getPriority() method can be used to
find the current value of the priority of a thread.
Daemon 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.
Scheduling example
The following applet demonstrates the execution of two threads with different priorities.
One thread is running at the lowest priority and the other at the highest priority. The
threads will count until the faster thread's counter catches up to the slower threads
counter.
ScheduleThreads Example and source code
import java.applet.*;
import java.awt.*;
public class ScheduleThreads extends Applet
8. {
Counter low,high;
public void init()
{
low=new Counter(200);
high=new Counter(0);
low.setPriority(Thread.MIN_PRIORITY);
high.setPriority(Thread.MAX_PRIORITY);
System.out.println("high priority is
"+high.getPriority());
System.out.println("low priority is
"+low.getPriority());
}
public void start()
{
low.start();
high.start();
while(high.getCount()<low.getCount())
{
repaint();
}
repaint();
low.stop();
high.stop();
}
public void paint(Graphics g)
{
g.drawString("low = "+low.getCount()+ " high=
"+high.getCount(),10,10);
System.out.println("low = "+low.getCount()+ " high=
"+high.getCount());
}
public void stop()
{
low.stop();
high.stop();
}
}
public class Counter extends Thread
{
int Count;
public Counter()
{
Count=0;
}
public Counter(int x)
{
Count=x;
9. }
public void run()
{
while(true)
{
Count++;
try {
sleep(10);
} catch(InterruptedException e){}
}
}
public int getCount()
{
return Count;
}
}
Conclusion
Using threads in Java will enable greater flexibility to programmers looking for that extra
edge in their programs. The simplicity of creating, configuring and running threads lets
Java programmers devise portable and powerful applets/applications that cannot be made
in other third-generation languages. Threads allow any program to perform multiple tasks
at once. In an Internet-aware language such as Java, this is a very important tool.
Author Bio
Donald G. Drake has been programming in Java since the alpha release. Drake has
written applets designed to spice up web sites. The most popular is his version of a
TickerTape (http://www.netobjective.com/java/TickerTapeInfo.html), which can be
extensively configured to blend into any web page. Drake's background includes a
Bachelor of Science degree in Computer Science from John Carroll University. He is
currently pursuing a Masters of Science Degree at DePaul University.