search
HomeJavajavaTutorialA brief introduction to JAVA

A brief introduction to JAVA

Jun 23, 2017 pm 01:52 PM
notesIntroductionread

Brief History

Early computers did not include an operating system. Only one program was executed from beginning to end, and this program had access to all resources of the computer. With the development of computers and the emergence of operating systems, computers can run multiple programs at the same time, and each program runs in a separate process. Why do you do that? Mainly based on the following reasons:

1.Resource Utilization The computer can execute another program while the program is waiting, and the same resource can be used by different programs, which undoubtedly improves resource utilization. .
2.Fairness Different users and programs have the same right to use the computer. Each program shares resources through time slicing, instead of waiting for the previous program to finish running before starting the next program.
3.Convenience Each program runs independently and communicates with each other when necessary, which is easier to implement than one program completing all tasks.

Since computers have developed from single tasks to multi-tasks, programs can naturally develop from traditional serial programs to concurrent programs.

The advantage of serial programs is that they are simple and intuitive. But the above three reasons also prompted the emergence of threads. The above computers can run programs in separate processes, and threads allow multiple program control flows to exist in the same process. Multiple threads of a program can also be scheduled to run by multiple CPUs at the same time. This is equivalent to the computer executing multiple programs (processes) at the same time, and the program executing multiple threads at the same time. That is, running threads within the process.

Threads are also called lightweight processes. Today's operating systems are scheduled with threads as the basic unit. Since resources are shared between threads, if there is no clear synchronization mechanism, it will lead to disordered execution between threads, data errors or failures, and exceptions. This is often where the difficulty lies in concurrent programming.

From my point of view, the so-called concurrent programming is the use of threads. Threads can convert many asynchronous workflows into serial workflows, and concurrent programming is to achieve synchronization in asynchronous situations to make it meet the needs.

So what are the advantages and risks of threads?

Thread Advantages

Threads can effectively reduce program development and maintenance costs and improve performance. Reduce code complexity and better simulate human working methods.

Advantage 1. Give full play to the powerful functions of multi-processors. Multi-processor systems are becoming more and more perfect, making the role of threads particularly obvious. Since different threads can be scheduled by multiple processors at the same time, especially during I/O operations, the waiting time of the program is reduced. Multi-processors improve the efficiency of program execution, thereby expanding the throughput of the system.
Advantage 2. Reduce the difficulty of modeling. It is easier to do the same thing all the time than to do many things. Use threads to refine program tasks and assign multiple tasks to multiple threads. Each thread has a single task and communicates with each other when necessary. It is less expensive than a single thread to switch tasks back and forth.
Advantage 3. Simplify asynchronous event processing When a request is issued to wait for a response, does the entire program have to wait? This means that all other requests will be stalled. Just like when chatting, the other party must reply before you can say the next sentence. This is obviously unreasonable. If each request is processed by a thread, the threads are independent and do not affect each other, which solves the problem. Of course, if you must know what the other party said when replying in a chat, pay attention to thread safety.
Advantage 4. More responsive user interface Traditional GUI programs are single-threaded. If one of the user events takes too long to process, the entire program will be stuck, making the user experience worse. If some time-consuming operations are assigned to a separate thread, other events will still be processed by the thread, which will make the user interface smooth.

Thread Risk

Thread support is a double-edged sword, and the development of concurrent programs also brings higher level requirements to programmers.

Risk 1. Security issues Concurrent programming may cause errors that do not occur in single-threaded programs.
Risk2. Liveness problem The definition of liveness is "something right will definitely happen." Infinite loops in a single thread are liveness issues. If thread A waits for thread B to release the resources it holds, and thread B has not released it, thread A will wait forever. This is an activity problem.
Risk 3. Performance issues Performance is "the right thing happens as quickly as possible." Good concurrency design will improve performance, and vice versa will reduce performance. After all, starting threads also consumes resources.

There is a good example about security:

value++;

With just this line of code, there is no problem at all in a single-threaded program, but unexpected consequences may occur in multi-threaded programs.

There are three steps to execute this line of code: 1. Read value; 2. Add 1 to value; 3. Assign the added value back to value. The program may be executed alternately by multiple threads. During this period, if two threads read the value at the same time, get the same value, and add 1 to it at the same time, the result is that different threads get the same value. And our expectation is that this value is added twice.

Every Java program uses threads. Even if you create threads without explicitly creating them in the program, the framework you use is still creating threads. These threads must be thread-safe.

The above is the detailed content of A brief introduction to JAVA. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.