Java Multithreading <1>

Source: Internet
Author: User

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 &lt;1&gt;

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.