Tag Archives: Thread

[Solved] AttributeError: module ‘thread‘ has no attribute ‘start_new_thread‘

There is a package name thread in the project (the folder name in Python is also the package name), which conflicts with the thread library of the system. Just rename the folder in the project.

That is, change thread.py in the project to another name.

Right click thread.py → refactor → rename → in pycharm to change the name to be different from the system thread library.

[Solved] Jetson Nano catkin_make Error: internal compiler error

When Jetson Nano compiles with catkin_make, if the default is 4 threads (catkin_make -j4), internal compiler error is prone to occur. At this time, you can modify ~/.bashrc to change the number of threads compiled by the system to limit the maximum thread. Thus it compiles smoothly. Proceed as follows:
1. Open terminal

vim ~/.bashrc

2. Add the following command, n is the number of threads you want to set, for example, it is better to set it to 2 or less for Nano:

export ROS_PARALLEL_JOBS=-jn  # Nano n=2

3. Source it to take effect:

source ~/.bashrc

OK, you can experiment happily~

[example multitasking] Python multithreading module

Python has built-in threading module, which encapsulates the lower level thread module
for built-in methods, see the official document: threading – thread based parallelism

Multithreading execution

The main thread will wait for all the child threads to finish

#coding=utf-8
import threading
import time

def thread_test():
    print("test.")
    time.sleep(1)

if __name__ == "__main__":
    for i in range(5):
        t = threading.Thread(target=thread_test)
        t.start() 

View the number of threads

#coding=utf-8
import threading
from time import sleep, ctime

def a():
    for i in range(3):
        print("a...%d"%i)
        sleep(1)

def bbbbb():
    for i in range(3):
        print("bbbbb...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---start---:%s'%ctime())
    t1 = threading.Thread(target=a)
    t2 = threading.Thread(target=bbbbb)

    t1.start()
    t2.start()

    while True:
        length = len(threading.enumerate())
        # length = threading.active_count()
        print('The number of threads currently running is: %d'%length)
        if length<=1:
            break

        sleep(0.5)

Encapsulating the threading. Thread class

Inherit threading. Thread and override run method

#coding=utf-8
import threading
import time

class MyThread(threading.Thread):

    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i) The name of the current thread is stored in the #name attribute
            print(msg)


if __name__ == '__main__':
    t = MyThread()
    t.start()

Thread execution order

Each thread runs a complete run function, but the start order of the thread and the execution order of each loop in the run function cannot be determined.

Sharing global variables and passing parameters

# Shared global variables
from threading import Thread
import time

g_num = 100

def work1():
    global g_num
    for i in range(3):
        g_num += 1
    print("----in work1, g_num is %d---"%g_num)


def work2():
    global g_num
    print("----in work2, g_num is %d---"%g_num)


print("---Before the thread is created g_num is %d---"%g_num)

t1 = Thread(target=work1)
t1.start()

#Delay for a while to make sure things are done in thread t1
time.sleep(1)

t2 = Thread(target=work2)
t2.start()

All threads in a process share global variables, which is very convenient to share data among multiple threads. Disadvantages: threads change global variables randomly, which may cause confusion among multiple threads (that is, threads are not safe)

from threading import Thread
import time

def work1(nums):
    nums.append(44)
    print("----in work1---",nums)


def work2(nums):
    #Delay for a while to make sure things are done in thread t1
    time.sleep(1)
    print("----in work2---",nums)

g_nums = [11,22,33]

t1 = Thread(target=work1, args=(g_nums,))
t1.start()

t2 = Thread(target=work2, args=(g_nums,))
t2.start()

Mutex

When multiple threads modify a shared data almost at the same time, synchronization control is needed.
when a thread wants to change the shared data, lock it first. At this time, the resource status is “locked”, and other threads cannot change it; Until the thread releases the resource and changes its state to “non locked”, other threads can lock the resource again. Mutex ensures that only one thread can write each time, so as to ensure the correctness of data in the case of multithreading.

Advantages ensure that a piece of key code can only be completely executed by one thread from beginning to end. Disadvantages 1 prevent the concurrent execution of multiple threads. In fact, a piece of code containing locks can only be executed in single thread mode, which greatly reduces the efficiency. Disadvantages 2 because there can be multiple locks, different threads hold different locks, and try to obtain the lock held by the other party, Deadlock may occur

import threading
import time

g_num = 0

def test1(num):
    global g_num
    for i in range(num):
        mutex.acquire()  
        g_num += 1
        mutex.release()  

    print("---test1---g_num=%d"%g_num)

def test2(num):
    global g_num
    for i in range(num):
        mutex.acquire()  
        g_num += 1
        mutex.release()  

    print("---test2---g_num=%d"%g_num)

# Create a mutually exclusive lock
# Default is the unlocked state
mutex = threading.Lock()

# Create 2 threads and have them each add 1000000 times to g_num
p1 = threading.Thread(target=test1, args=(1000000,))
p1.start()

p2 = threading.Thread(target=test2, args=(1000000,))
p2.start()

# Wait for the calculation to complete
while len(threading.enumerate()) ! = 1:
    time.sleep(1)

print("The final result after 2 threads operate on the same global variable is:%s" % g_num)

Mutex can use context manager
to use lock, condition and semaphore in with statement
the object with acquire() and release() method provided by this module can be used as context manager of with statement. When entering a statement block, the acquire () method will be called, and when exiting a statement block, release () will be called. Therefore, the following fragments:

with some_lock:
    # do something...

# Equivalent to :

some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()

Lock, RLOCK, condition, semaphore, and boundedsemaphore objects can now be used as context managers for the with statement.

Multithreading case [chat]

Write a program with two threads
thread 1 is used to receive data and then display
thread 2 is used to detect keyboard data and then send data through UDP

import socket
import threading


def send_msg(udp_socket):
    """Get the keyboard data and send it to the other side """
    while True:
        # 1. input data from keyboard
        msg = input("\nPlease enter the data to be sent:")
        # 2. enter the ip address of the other party
        dest_ip = input("\nPlease enter the other party's ip address:")
        # 3. enter the other party's port
        dest_port = int(input("\nPlease enter the other party's port:"))
        # 4. send data
        udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port))


def recv_msg(udp_socket):
    """Receive data and display """
    while True:
        # 1. receive data
        recv_msg = udp_socket.recvfrom(1024)
        # 2. decode
        recv_ip = recv_msg[1]
        recv_msg = recv_msg[0].decode("utf-8")
        # 3. display the received data
        print(">>>%s:%s" % (str(recv_ip), recv_msg))


def main():
    # 1. Create a socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 2. bind local information
    udp_socket.bind(("", 7890))

    # 3. create a child thread to receive data
    t = threading.Thread(target=recv_msg, args=(udp_socket,))
    t.start()
    # 4. let the main thread detect the keyboard data and send
    send_msg(udp_socket)


if __name__ == "__main__":
    main()

Asynchronous callback case of Java callback function

1. Callback function classification

Callback function distinction: synchronous callback and asynchronous callback

Synchronous callback: the meaning is only to complete the method call;

Asynchronous call: concurrency can be realized, and the main business thread can be released in time; asynchronous thread completes the work, executes callback function, and completes the aftermath work; the execution efficiency is improved.

2. Code examples

1. Note testing

package com.callback2;

public class AsyncCallBack {

    public static void main(String[] args) {
        System.out.println("Start of the main business thread ID:" + Thread.currentThread().getId());
        System.out.println("------------------");

        Son son = new Son();
        Mother mother = new Mother(son);

        mother.notice();
        son.writeHomeWork();

        System.out.println("End of the main business thread ID:" + Thread.currentThread().getId()+"\n");

    }

}

2. Mother

package com.callback2;

public class Mother {
    private Son son;
    public Mother(Son son) {
        this.son = son;
    }

    public void notice() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Notify the mother of the thread ID." + Thread.currentThread().getId());
                cookFood("Bread");
            }
        }).start();
    }

    public void cookFood(String bread) {
        System.out.println("Current cooking thread ID." + Thread.currentThread().getId());
        try {
            System.out.println("Mother Baking" + bread + "...");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Mother has baked the bread");
        String message = "Ming, come and eat!";

        son.callback(message);

    }

}

3. My son Xiao Ming

package com.callback2;

public class Son {
    private String status = "";

    public void writeHomeWork() {
        System.out.println("Xiaoming writing homework thread ID: " + Thread.currentThread().getId());
        System.err.println("Ming is writing his homework...") ;
        setStatus("Writing homework");
    }


    public void callback(String message) {
        System.out.println("Callback Xiaoming meal thread ID: " + Thread.currentThread().getId());
        System.err.println(message);
        System.err.println("Okay, coming right up!") ;
        System.out.println("Ming started eating!") ;
        setStatus("Eating in progress");
        System.out.println("Xiaoming executing meal thread ID." + Thread.currentThread().getId());
    }

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}

4. Implementation results

Business Main Thread Start ID: 1
------------------
Xiaoming writing homework thread ID: 1
Xiaoming writing homework in progress...
Business main thread end ID:1

Notify mother thread ID:12
Currently cooking thread ID:12
Mother baking bread...
Mother baked the bread
Callback to Xiaoming to eat Thread ID: 12
Ming, come and eat!
Okay, coming right up!
Ming starts eating!
Xiaoming executes meal thread ID: 12

5. Result analysis

1) Xiao Ming uses the main thread to do his homework (if he can’t finish it, he doesn’t need to care);

2) Mother uses the new thread to cook [concurrent], mother finishes the meal, executes the callback function, and notifies Xiao Ming to eat;

3) Xiao Ming uses a new thread and starts to eat.

Solution of toast not displaying in Android

Today, in the test, toast could not be displayed. I analyzed several possibilities

1. There is a problem with the context. The corresponding context may be incorrect

2. The value of message is null

But I checked it several times and there was no problem…. Looking up information on the Internet, I said that I couldn’t update UI in sub thread, but I didn’t open thread… After a night of silence. I found the problem. After using toast, I didn’t call the show method… That’s why I don’t show it. It’s too sloppy…

0xc0000005: an access conflict occurred while reading location 0x00000020

0x in.exe… Unhandled exception at: 0xC0000005: Access conflict occurred while reading position 0x00000020

Error: : PostMessage (AfxGetMainWnd () – & gt; M_hWnd, UM_XX, 0, 0);

or: : sendMessage (
AfxGetMainWnd()-> M_hWnd, UM_XX, 0, 0);

How to solve it?
Verify that afxGetMainWnd () returns NULL

int k = (int)(& (((CWnd*)NULL)-> m_hWnd));
The value of k is 0x20

In general: afXGetApp ()-> GetMainWnd (); AfxGetMainWnd() is used only on the main thread;

How: foreground thread and background thread, afxGetApp ->; GetMainWnd() differs from AFXGetMainWnd ()

AFXGetMainWnd () is an example of a window handle that can be used to retrieve a window handle. AFXGetMainWnd () is an example of a window handle that can be used to retrieve a window handle. Clever you must have already understand, if you have been tracking AfxGetMainWnd () call, will find that it earned a AFX_MODULE_THREAD_STATE threading module save active threads in the window handle, and a background thread since no window, then obtains the window handle is you from??(maybe someone’s understanding of the background is not display window, even with all the window, as long as it doesn’t show is a background thread, strictly speaking is not the case, the window is mainly used to interact with the user, a window is hard to avoid jam, And the background thread is often used to carry out some behind the operation or processing, is through the foreground information or data to carry out the corresponding operation, if the window is hidden to talk about what information transfer?The case can not be done in the background like other threads. The key is to know the difference and how to use it.)
AfxGetApp()-> GetMainWnd () is the main window handle, no matter in that thread calls are no problem, because it is first obtained the main thread handle, to achieve the main thread of the active window (such as switch view can lead to replacement, I am not sure this kind of circumstance), if there is no active window is the main window, any program must have a main window, so it calls there is no problem, if you want to achieve the program’s main window suggested AfxGetApp () – & gt; GetMainWnd().
Note that the console program has no window and its window handle is always 0. Second, the background thread is actually a desktop control program, just not the main thread. Also, threads created using functions such as API CreateThread cannot generate CWinThread objects. So if you want to use CWinThread object function, and some of the global function, as AfxGetMainWnd (), you must use CWinThread object CreateThread function, or use the AfxBeginThread () function creates a thread, or may be an error, because the MFC to the management of the thread is done through the CWinThread object, it is not hard to see through the tracking code below you. I remember that there was a predecessor once mentioned this problem, but I do not know whether it understands the reason
Here is the trace code:
_AFXWIN_INLINE CWnd* AFXAPI AfxGetMainWnd()
{ CWinThread* pThread = AfxGetThread();
return pThread! = NULL ?pThread-> GetMainWnd() : NULL; }

CWinThread* AFXAPI AfxGetThread()
{
// check for current thread in module thread state
AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();
CWinThread* pThread = pState-> m_pCurrentWinThread;
// if no CwinThread for the module, then use the global app
if (pThread == NULL)
hread = afxGetApp ();
return pThread;
}
You can see that calling afxgetMainwnd () on the main thread is not a problem (except for console programs) because it returns the main thread handle if the fetched thread handle is empty.
_AFXWIN_INLINE CWinApp* AFXAPI AfxGetApp()
{ return afxCurrentWinApp; }

CWnd* CWinThread::GetMainWnd()
{
if (m_pActiveWnd ! = NULL)
return m_pActiveWnd;// probably – place in active
// when not inplace active, just return main window
if (m_pMainWnd ! = NULL)
return m_pMainWnd;
return CWnd::GetActiveWindow();
}
I don’t need to worry about AFXCurrentInApp.
Hey hey, all finished, if your program exists similar to the above problems can be sure to change back oh.

Python error unhandled exception in thread started by error in sys.excepthook

import time
import thread
def timer(no, interval):
 cnt = 0
 while cnt<10:
 print 'Thread:(%d) Time:%s/n'%(no, time.ctime())
 time.sleep(interval)
 cnt+=1
 thread.exit_thread()
 
def test(): #Use thread.start_new_thread() to create 2 new threads
 thread.start_new_thread(timer, (1,1))
 thread.start_new_thread(timer, (2,2))
 
if __name__=='__main__':
 test()

There is an error
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
Solution: Change the main function to

<pre>if __name__=='__main__':
 test()
time.sleep(3)

As for why sleep for a few seconds, not clear

The message on the Web is that threading is not recommended, use the threading.thread class instead

[How to Fix] org.apache.cxf.binding.soap.SoapFault: Error reading XMLStreamReader.

org.apache.cxf.binding.soap.SoapFault: Error reading XMLStreamReader.
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:230)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:60)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:244)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:729)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2261)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2134)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1988)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:639)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:244)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
at $Proxy54.save(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:54)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:54)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy55.save(Unknown Source)
at org.rtx.wmprd.test.TestAsnServices.main(TestAsnServices.java:37)
Caused by: com.ctc.wstx.exc.WstxIOException: Invalid UTF-8 middle byte 0xde (at char #541, byte #127)
at com.ctc.wstx.sr.StreamScanner.throwFromIOE(StreamScanner.java:708)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1086)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:218)
... 32 more
Caused by: java.io.CharConversionException: Invalid UTF-8 middle byte 0xde (at char #541, byte #127)
at com.ctc.wstx.io.UTF8Reader.reportInvalidOther(UTF8Reader.java:313)
at com.ctc.wstx.io.UTF8Reader.read(UTF8Reader.java:204)
at com.ctc.wstx.io.MergedReader.read(MergedReader.java:101)
at com.ctc.wstx.io.ReaderSource.readInto(ReaderSource.java:84)
at com.ctc.wstx.io.BranchingReaderSource.readInto(BranchingReaderSource.java:57)
at com.ctc.wstx.sr.StreamScanner.loadMore(StreamScanner.java:992)
at com.ctc.wstx.sr.StreamScanner.loadMore(StreamScanner.java:1034)
at com.ctc.wstx.sr.StreamScanner.getNextChar(StreamScanner.java:794)
at com.ctc.wstx.sr.BasicStreamReader.parseNormalizedAttrValue(BasicStreamReader.java:1900)
at com.ctc.wstx.sr.BasicStreamReader.handleNsAttrs(BasicStreamReader.java:3037)
at com.ctc.wstx.sr.BasicStreamReader.handleStartElem(BasicStreamReader.java:2936)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2848)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1019)
... 33 more
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:146)
at $Proxy54.save(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:54)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:54)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy55.save(Unknown Source)
at org.rtx.wmprd.test.TestAsnServices.main(TestAsnServices.java:37)
Caused by: com.ctc.wstx.exc.WstxIOException: Invalid UTF-8 middle byte 0xde (at char #541, byte #127)
at com.ctc.wstx.sr.StreamScanner.throwFromIOE(StreamScanner.java:708)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1086)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:218)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:60)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:244)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:729)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2261)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2134)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1988)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:639)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:244)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
... 17 more
Caused by: java.io.CharConversionException: Invalid UTF-8 middle byte 0xde (at char #541, byte #127)
at com.ctc.wstx.io.UTF8Reader.reportInvalidOther(UTF8Reader.java:313)
at com.ctc.wstx.io.UTF8Reader.read(UTF8Reader.java:204)
at com.ctc.wstx.io.MergedReader.read(MergedReader.java:101)
at com.ctc.wstx.io.ReaderSource.readInto(ReaderSource.java:84)
at com.ctc.wstx.io.BranchingReaderSource.readInto(BranchingReaderSource.java:57)
at com.ctc.wstx.sr.StreamScanner.loadMore(StreamScanner.java:992)
at com.ctc.wstx.sr.StreamScanner.loadMore(StreamScanner.java:1034)
at com.ctc.wstx.sr.StreamScanner.getNextChar(StreamScanner.java:794)
at com.ctc.wstx.sr.BasicStreamReader.parseNormalizedAttrValue(BasicStreamReader.java:1900)
at com.ctc.wstx.sr.BasicStreamReader.handleNsAttrs(BasicStreamReader.java:3037)
at com.ctc.wstx.sr.BasicStreamReader.handleStartElem(BasicStreamReader.java:2936)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2848)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1019)
... 33 more

When using Apache CXF, the above exception appears in the calling method. After careful inspection, the ASM package is missing. Just introduce the ASM package.

The difference between sleep() and wait() in Java

learning just encounter these two methods, look up relevant information, and through the program to achieve, the difference:

Each object has a lock to control access to the synchronization, and the Synchronized keyword can interact with an object’s lock to implement Synchronized methods or blocks. sleep() sleep() lock lock! ). wait () method is refers to the current thread to temporarily retreat out the synchronous resource lock, so that other threads are waiting for the resource to get the resources, in turn, to run, only calls the notify () method, before calling wait () thread will lift its state of wait, can go to participate in the competition synchronous resource locks, and enforced. ( note: notify role is equivalent to wake the sleeping man, and would not give his assigned task, that is to say notify calling wait before just let the thread has the right to participate in the thread scheduling ).

2, sleep() can be used anywhere; wait() method can only be used in synchronized methods or synchronized blocks;

3, sleep() is the method of Thread. The call will suspend the specified time of this Thread, but the monitoring will still be maintained, and the object lock will not be released, and it will automatically recover at the time. wait() is an Object method. The call will give up the Object lock and enter the wait queue. The call notify()/notifyAll() will wake up the specified thread or all threads to enter the lock pool and run until the Object lock is acquired again.


to procedures:

public class MultiThread {

	private static class Thread1 implements Runnable{		
		@Override
		public void run() {
			//由于 Thread1和下面Thread2内部run方法要用同一对象作为监视器,如果用this则Thread1和Threa2的this不是同一对象
			//所以用MultiThread.class这个字节码对象,当前虚拟机里引用这个变量时指向的都是同一个对象
			synchronized(MultiThread.class){
				System.out.println("enter thread1 ...");
				System.out.println("thread1 is waiting");
				
				try{
					//释放锁有两种方式:(1)程序自然离开监视器的范围,即离开synchronized关键字管辖的代码范围
					//(2)在synchronized关键字管辖的代码内部调用监视器对象的wait()方法。这里使用wait方法
					MultiThread.class.wait();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				System.out.println("thread1 is going on ...");
				System.out.println("thread1 is being over!");
			}
		}
		
	}
	
	private static class Thread2 implements Runnable{
		@Override
		public void run() {	
			//notify方法并不释放锁,即使thread2调用了下面的sleep方法休息10ms,但thread1仍然不会执行
			//因为thread2没有释放锁,所以Thread1得不到锁而无法执行
			synchronized(MultiThread.class){
				System.out.println("enter thread2 ...");
				System.out.println("thread2 notify other thread can release wait status ...");
				MultiThread.class.notify();
				System.out.println("thread2 is sleeping ten millisecond ...");
				
				try{
					Thread.sleep(10);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				System.out.println("thread2 is going on ...");
				System.out.println("thread2 is being over!");
			}
		}		
	}
	
	public static void main(String[] args) {
		new Thread(new Thread1()).start();
		try{
			Thread.sleep(10);
		}catch(InterruptedException e){
			e.printStackTrace();
		}

		new Thread(new Thread2()).start();
	}

}

program results as shown in the figure below