Java Multithreading <1>

Source: Internet
Author: User

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>

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.