1. Java Multi-Threading concept:
Line (thread): it refers to a task from the beginning of the execution process to the end.
Threading provides the authority to perform the task. For Java terms. In a program you can start multiple concurrent threads. Waiting to be executed.
在单处理器系统中,多个线程共享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 simple, such as the following:
publicabstractinterface java.lang.Runnable { // Method descriptor #1 ()V publicabstractvoidrun();}
There is only one run method in the interface that requires this method to tell the system how the thread will execute. The following describes how to develop a task class:
1. Once a taskclass is defined, it is possible to create a task with his own method of construction. Like what:
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 execute
thread.start();
Let me give you a simple example of this:
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
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Java Multithreading <1>