Java multithreading (1) and java Multithreading

Source: Internet
Author: User

Java multithreading (1) and java Multithreading

1 public class ThreadA extends Thread {2 private static int threadID = 0; 3 4 public ThreadA () {5 super ("ThreadID:" + (++ threadID )); 6} 7 8 public void run () {9 try {10 System. out. println (getName () + "the thread starts running! "); 11 for (int I = 0; I <10; I ++) {12 System. out. println (this. getName () + "is" + I); 13 14 Thread. sleep (1); // sleep is required here, otherwise the effect of multithreading cannot be seen. 15} 16} catch (Exception e) {17 e. printStackTrace (); 18} 19} 20 21}
public class MyTest {    public static void main(String[] args){        ThreadA t1=new ThreadA();        ThreadA t2=new ThreadA();        t1.start();        t2.start();    }}

Input result:

ThreadID: 1. The thread starts running!
ThreadID: 1 is 0
ThreadID: 2. The thread starts to run!
ThreadID: 2 is 0
ThreadID: 1 is 1
ThreadID: 2 is 1
ThreadID: 1 is 2
ThreadID: 2 is 2
ThreadID: 1 is 3
ThreadID: 2 is 3
ThreadID: 1 is 4
ThreadID: 2 is 4
ThreadID: 1 is 5
ThreadID: 2 is 5
ThreadID: 1 is 6
ThreadID: 2 is 6
ThreadID: 1 is 7
ThreadID: 2 is 7
ThreadID: 1 is 8
ThreadID: 2 is 8
ThreadID: 1 is 9
ThreadID: 2 is 9


How to Learn multithreading in java

Almost all drawing programs written using AWT or Swing require multithreading. However, multi-threaded programs may cause many difficulties. developers who are new to programming often find that they are suffering from problems such as incorrect program behavior or deadlocks.

In this article, we will discuss the problems encountered when using multithreading and propose solutions to common traps.

What is a thread?
A program or process can contain multiple threads, which can execute corresponding commands Based on the program code. Multithreading seems to be executing their respective jobs in parallel, just like running multiple processors on a computer. When multithreading is implemented on a multi-processor computer, they can indeed work in parallel. Unlike the process, the thread shares the address space. That is to say, multiple threads can read and write the same variable or data structure.

When writing multi-threaded programs, you must pay attention to whether each thread interferes with the work of other threads. The program can be seen as an office. If you do not need to share office resources or communicate with others, all employees will work independently and concurrently. If an employee wants to talk to others, and only when the employee is "listening" and both of them speak the same language. In addition, employees can use the photocopier only when it is idle and available (not only half of the copy work is completed, no problems such as paper blocking. In this article, you will see that the threads that collaborate in Java programs are like employees who work in a well-organized organization.

In multi-threaded programs, threads can be obtained from the ready queue and run on the available system CPU. The operating system can move the thread from the processor to the ready queue or block the queue. In this case, the processor "suspends" the thread. Similarly, Java Virtual Machine (JVM) can also control the movement of threads ?? In collaboration or preemptive model ?? The process is moved from the ready queue to the processor, so the thread can start to execute its program code.

The collaborative thread model allows the thread to decide when to discard the processor to wait for other threads. Developers can accurately determine when a thread will be suspended by other threads and allow them to cooperate effectively with each other. The disadvantage is that some malicious or poorly written threads consume all the available CPU time, resulting in other threads being "Hungry ".

In the preemptible thread model, the operating system can interrupt the thread at any time. It is usually interrupted after it runs for a period of time (called a time slice. The result is that no thread can occupy the processor for a long time. However, interrupting the thread at any time may cause other troubles for the program developer. In the same example of using the office, assume that a clerk snatched another person to use the photocopier, but the print work left when the work was not completed, and the other person continued to use the photocopier, there may be materials from the previous employee on the photocopier. The preemptible thread model requires threads to correctly share resources, while the collaborative model requires threads to share the execution time. Since the JVM specification does not specify a thread model, Java developers must write programs that can run correctly on both models. After learning about threads and communication between threads, we can see how to design programs for these two models.

Thread and Java language
To create a Thread in Java, you can generate an object of the Thread class (or its subclass) and send a start () message to the object. (The program can send a start () message to any class object derived from the Runnable interface .) The definition of each thread action is included in the run () method of the thread object. The run method is equivalent to the main () method in a traditional program. The thread will continue to run until run () returns, and the thread will die.

Lock
Most applications require threads to communicate with each other to synchronize their actions. The simplest way to implement synchronization in Java is locking. To prevent simultaneous access to shared resources, the thread can lock and unlock the resource before and after the resource is used. Imagine locking the photocopier. At any time, only one employee has a key. The photocopier cannot be used without a key. Locking shared variables enables Java threads to communicate and synchronize quickly and conveniently. If a thread locks an object, it can know that no other thread can... the remaining full text>
 
How to Learn java multithreading?

Learning Java should actually rise to the realm of How to Learn program design. In fact, learning program design also accepts a programming idea. The program design concepts of each language are similar, but they are just some minor differences brought about by the language characteristics. For example, interfaces in Java, you have hardly encountered them in your previous studies. The following 9 points are the study notes summarized by "xiao shu's blog". I hope it will help you !!
1. We must clarify a general direction, that is, the current Object-Oriented Programming scope. Although artificial intelligence has a wave (to see why Borland has TurboProlog), in the next 5-10 years, the industry will widely recognize and accept object-oriented programming.
2. Currently, the most popular object-oriented programming languages in the industry are C ++ and Java. So we can basically lock these two directions. And can be mastered at the same time.
3. Master the essential features of Java and be sure to know why. For example, Interface and multi-thread. Using Interfaces is a better model of multi-inheritance, while multithreading is an important feature designed at the language level. We need to fully understand why the interface is, and there are several common programming models with multithreading.
4. After understanding the characteristics of a language, you can try to rise to the design level. After all, you need to learn the language. Currently, a better development mode is a custom object-oriented design, coupled with the MVC pattern (you can take a look at the content I introduced about MVC ). First, we need to find the objects at the top level (which is often the most difficult), and then layer-by-layer recursion. Remember that each time we meet the principle of 7 +/-2, because our short memory is like this. Generally, the graphic user interface should be designed from the interface.
5. With the basic Design model, you can learn some Design patterns ). This is currently proven to be effective. For example, hierarchy,
Pipe/Filter pipelines or filters), design patterns (such as Object Pool in the Object Pool and buffer Pool Cache), and programming patterns (such as Copy-on-Write ).
After understanding these models, we will have a good grasp of the overall structure of the system, and there is also a tendency for an academic system to be composed of various models. The MT mentioned above actually has several modes, so you don't have to spend a lot of time trying it on your own. Another very important field is the parallel and distributed computing field, with about 20 types.
6. Next we can't talk about it on paper. The best method is practice. In general, examples in textbooks cannot be regarded as practices. They can only be used to help you master the language features. It is not very good to advocate the practical Project, because you have not yet mastered the ability to integrate various technologies, so that you are more and more confused. I think the better way is to find some classic examples. Each example is designed by comparing a programming idea in the set. From HotDraw, I learned what Framework is and how to construct it using rolemodel, so that I can apply it to other places. By the way, you will never think of this example as small, but as big as a commercial Framework.
7. With the previous design patterns, you can understand these classic examples. And you can use it to implement some simple systems. If you can make further modifications to him, find out what you think can improve the performance, and add your own design, it will become a higher level, and you will truly feel some gains.
8. It seems that the above talk has nothing to do with Java. In fact, we should have gone from simply learning the language to truly learning the programming field. There is no end to learning technology. It may take six months for you to learn the first language. In the future, every language should not be more than two months. Otherwise, you will feel that language learning is a burden and a pain point.
9. Learning is used to create value for your program. It is easier to grasp this principle.
... The remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.