Threads for Java

Source: Internet
Author: User

Multitasking and Multithreading: multi-tasking is a relationship between applications at the system level, and multithreading is a relationship between multiple functions of an application-level app

There are two ways to create a thread:

Implementing the Runnable Interface

Class Sunclass {}

Class Sumthread extends Sumclass imlements runnable{}

public class **{public void Main () {Sumthread st=new sumthread (); thread t=new thread (St, "ThreadName"); T.start ();}}

Inheriting the thread class (directly inheriting the thread class, or using anonymous nested classes)

classSumthread extends thread{Private Longlength;  PublicSumthread (Longlength,string name)        {super (name);  This. length=length; }     Public voidrun () {Longtemp=0;  for(intI=1; i<=length;i++){            Try{Thread.Sleep (int) (Math.random () *Ten)); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } temp+=i; } System. out. println (Thread.CurrentThread () +"Zonghe:"+temp); }} Public classThread1 { Public Static voidMain (string[] args) {System. out. println ("Threads"); System. out. println (Thread.CurrentThread ()); Sumthread St1=NewSumthread ( Max,"Thread 1");        St1.start (); NewThread ("Thread 2"){            intLength= Max;  Public voidrun () {Longtemp=0;  for(intI=1; i<=length;i++){                    Try{Thread.Sleep (int) (Math.random () *Ten)); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } temp+=i; } System. out. println (Thread.CurrentThread () +"Zonghe:"+temp); }}.start ();}}

Threads for Java

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.