11. Threads

Thread and Java

A thread is a flow of execution of a task (job) from beginning to end

One of the powerful features of Java is its support for multi-threading


Main Thread

When you run a Java program, JVM starts a thread called the main thread which looks for the main method of the class you load


Event Dispatch Thread

Swing event handing code runs on a special thread called the event dispatch thread which takes care of user interface events (ToDoSwingGUI.java)


Problem: Continuously Updating

My app will constantly be displaying status

I want to be able to let the user interact with the UI to update the display

To make GUI Applications respontive,

- Event Dispatch Thread should only be in charge of short tasks

- Should use seperate thread(s) for any long tasks


Your thread

Use Thread.currentThread()

Your thread's name: Thread.currentThread().getName()

using Thread.sleep()

- Temporarily suspends the execution of the current thread for a given number of milliseconds to allow other threads (if there are existed) to execute


Making More Threads (Recipe1)

1. Place code for a task into a class that implements Runnable Interface and instantiate it: 

Runnable r = new MyRunnable();

2. Use new Thread(r) to create a new thread

- Object r must implement Runnable Interface

3. Use start() method on the thread


Runnable Interface and its run() method

The class must implement Runnable Interface

public class MyRunnable implements Runnable {
    public MyRunnable(...) {
        ...
    }

    @Override
    public void run() {
        ...
    }
    ...
}

Invoking start() method

Do not invoke run() method of the Thread or the Runnable object!

- execute the code in the run() method in the current thread

- No new thread is started

Call Thread.start() method

- Execute the run() method in new thread

Does NOT mean the new thread is actually running!

Also, once a thread is running, it does NOT necessarily keep running!

Up to JVM

- Generally speaking, it gives each thread an equal amount of time to perform its task

Again, remember a thread may or may not be running at ANY given time!


Thread States

New

- Thread t = new Thread(r);

- Not yet running

Runnable

- t.start();

- May or may not be actually running! It is up to JVM

Blocked (Time Waiting)

- Thread.sleep(1000);

Terminated

- run() completed


Examples (Recipe 1)

GUIs that print things with multiple threads:

MyRunnable.java

MyThreadWindow1.java

- Notice the main thread in the main method

- Notice the Event Dispatch Thread takes care of Swing events

- New runnable and thread are responsible for long-running tasks

- Each runnable instance has unique state (instance variable value)

- But all of the runnable instances execute the same run method


Note: Recipe 2

MyThread extends Thread

Either public class or private nested class that extends Thread

Advantages:

- You only need a reference to the "Thread"

- One less object

- Forces one thread per runnable object

- Thus, easier to reason about


Examples (Recipe 2)

GUIs that print things with multiple threads:

MyThread.java

MyThreadWindow2.java


Reasons to choose Recipe 1 (implements Runnable)

Decouple the task (Job) from the mechanism (Worker) of running it

Thread class can be a subclass of something else

- Java does NOT support multiple inheritance

Performance requires many threads sharing same job object

Logic requires many threads sharing same job object


Multi-Threaded and Shared Access

In most practical multi-threaded applications, two or more threads need to share access to the same data

The question is: What happen if two threads have access to the same object and each calls a method that modifies the state of the object?

Depending on the order, corrupted objects can result! (Race condition)


Race Conditions

When a program may or  may not execute correctly depending on how the threads are scheduled

Getting the right answer relies on lucky timing!


Synchronize the Access

To avoid race conditions, prevent more than one thread from simultaneously entering a certain part of the code

The synchronized statement can be used on objects (or on a method declaration)

- Only one thread at a time is allowed to enter into synchronized block or synchronized method, etc


What is the chance?

This kind of corruption may not happen when you test alone or with only a few people

May take a few minutes or hours or days or months to occur

There are few things worse than in the life of programmer than a bug that only shows up once every few hours, days, or months

- Race condition is one of them!

Remember a thread may or may not be running at any given time


Are Objects or Methods Thread-safe?

Not thread-safe: ArrayList, StringBuilder, etc

Thread-safe: Vector, StringBuffer, etc

- In general, Swing is not thread safe

- Swing text components provide some support of thread safe operations


Vectors vs. ArrayLists

Vectors were first

- Vectors are synchronized, ArrayLists are not synchronized

- Vectors did not follow the List interface

- The List interface methods were added for compatibility

For correct multithreaded access, you usually need to use an ArrayList protected with your own synchronized statements


StringBuffer vs. StringBuilder

StringBuffers were first

- StringBuffers are synchronized, StringBuilder are not synchronized

For correct multithreaded access, you usually need to use an StringBuilder protected with your own synchronized statements


Use the Unsynchronized Class?

Yes

Often no synchronization is required because only one thread is using an instance of a class

Often, when multiple threads using the same instance, you may still need to add EXTERNAL synchronization


Stopping Threads

Do NOT ever call Thread.stop()

- Caller can't determine or know whether the thread is at a safe point to be stopped, which is deprecated

One option is to use a method to tell the thread to stop, then let the thread exit run()

    private void setFinish() { finished = true; }
    public void run() {
        while(!finished) {...}
    }

Organizational Tip!

Calling Thread.sleep() method in a loop and try/catch

    try {
        ...
        while(...) {
            ...
            Thread.sleep(mySleepTimeInMillis);
        }
        ...
    } catch(InterruptedException e) {
        ...
    }

Question:

What's the difference between a thread and a process?

Threads

One shared address space

- Lots of little men concurrently executing in the *same* address spce

- can run without or with minimal OS or hardware support (for threads)

Processes

Lots of seperate address spaces

- Each process has separate memory

- Each can have one or more threads

- Requires OS support and usually hardware support


Sample Final Exam Questions

What does the synchronized modifier mean for a method declaration?

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object than one thread, all reads or writes to that object's variables are done through synchronized methods

- How is this related to the synchronized statement?

These are the same:

    // synchronized method
    public synchronized void f() {
        ...
    }

    public void f() {
        // synchronized block
        synchronized (this) {
            ...
        }
    }

What is a race condition?

When a program may or may not execute correctly depending on how the threads are scheduled

What does it mean for an object to be immutable?

Immutable means that once the constructor for an object has completed execution that instance can't be altered

Why is this important?

This is useful as it means you can pass references to the object around, without worrying that someone else is going to change contents. Especially when dealing with concurrency, there are no locking issues with objects that never change


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下问题如何修改jakarta.servlet.ServletException: 类text.HandlePassword不是Servlet org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:356) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:867) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1716) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748) 根本原因。 java.lang.ClassCastException: text.HandlePassword cannot be cast to jakarta.servlet.Servlet org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:356) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:867) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1716) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值