1. Java Multi-Threading concept:
Thread: Refers to the execution flow from beginning to end of a task. Threads provide a mechanism to run a task. For Java, you can start multiple threads concurrently in a program that can run concurrently on multiple processors.
在单处理器系统中,多个线程共享CPU时间,而操作系统负责调度及分配资源给它们。当程序作为一个应用程序来运行时,JAVA解释器为main开启一个线程。当程序为Applet运行时,Web浏览器启动一个线程来运行applet。还可以在程序中创建附加的线程以执行并发任务。在JAVA中,每个任务都是Runnable的实例。
2. Creating Tasks and Threads
A task is an object, in order to create a task, a class must be defined for the task, and the task class must implement the Runnable interface. The runnable interface is very simple, as follows:
publicabstractinterface java.lang.Runnable { // Method descriptor #1 ()V publicabstractvoidrun();}
There is only one run method in the interface, which requires this method to tell the system thread how to run it. The following describes how to develop a task class:
1. Once a taskclass is defined, it is possible to create a task using his constructor, for example:
TaskClass task = new TaskClass(参数);
2. The task must be executed in the thread.
Threadthread=newThread(task);
3. Call the Start () method to tell the Java virtual machine that the thread is ready to run
thread.start();
Let me give you a simple example:
Printchar.java
PackageCom.guigu.zhangxx.main; Public class Printchar implements Runnable{ Private CharCPrivate intNum Public Printchar(CharCintNUM) { This. C = C; This. num = num; } Public void Run() { for(intI=0; i<num;i++) {System.out.print (c+" "); } }}
Cmain.java
package com.guigu.zhangxx.main;publicclass CMain { publicstaticvoidmain(String[] args) { //创建任务 new PrintChar(‘A‘,10); //创建线程 new Thread(print1); //开启线程 thread1.start(); }}
The result is:
A A A A a a a a a a A
Java Multithreading <1>