search
HomeJavajavaTutorial[Java basics] Thread instance

[Java basics] Thread instance

Feb 07, 2017 am 10:58 AM

Today, a friend asked about the concept of Java multi-threading in the background. The editor thinks that only by mastering the basic thread concept can we have a deeper understanding of multi-threading. In layman's terms, it is multiple while loops running in parallel. If multiple things are done concurrently, multiple threads may operate on the same data block during actual use, so the problem of multi-threading arises. First, let’s understand the basic concepts of threads and simple code implementation

Classic examples of Java thread learning-reader and writer demonstration

The most classic example of Java thread learning-readers and writers, mainly using Thread related knowledge As follows:

-Thread start and run

-Thread sleep(sleep)

-Data object locking (synchronized)

-Data object Wait and release (wait and notify)

Program implementation:

-ObjectData data class object, locking is implemented through the synchronized keyword, and is used in thread readers and writers.

-ConsumerThread consumer thread, after reading the count value in the data object, notifies the producer thread

-ProductThread producer thread, operates on the count value in the data object, adding 1 each time, Then notify the consumer thread

The class structure diagram is as follows:

[Java basics] Thread instance

Code implementation

Consumer-reading thread

package com.gloomyfish.jse.thirdteen;
 
public class ConsumerThread extends Thread {
    private ObjectData data;
    public ConsumerThread(ObjectData data) {
        this.data = data;
    }
 
    @Override
    public void run() {
        while(true) {
            try {
                synchronized (data) {
                    data.wait();
                    data.read();
                    data.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
}

Write thread-producer thread

package com.gloomyfish.jse.thirdteen;
 
public class ProductThread extends Thread {
    private ObjectData data;
 
    public ProductThread(ObjectData data) {
        this.data = data;
    }
 
    @Override
    public void run() {
        while (true) {
            try {
                synchronized (data) {
                    data.write();
                    Thread.sleep(3000);
                    data.notify();
                    data.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
}

Data object class

package com.gloomyfish.jse.thirdteen;
 
public class ObjectData {
 
    private int count;
     
    public ObjectData() {
        count = 0;
    }
     
    public void read() {
        System.out.println("read count : " + count);
        System.out.println();
    }
     
    public void write() {
        count++;
        System.out.println("write count : " + count);
    }
}

Test code:

public static void main(String[] args) {
        ObjectData data = new ObjectData();
        ConsumerThread ct = new ConsumerThread(data);
        ProductThread pt = new ProductThread(data);
 
        ct.start();
        pt.start();
}

Summary:

The sample program code is completed between threads How to realize data reading and writing through wait and notify

Synchronous control. Demonstrates the usage of Java's synchronization keyword synchronized and the usage of threads.

The above is the content of [java basics] thread instance. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.