Java Multithreading--Implement Runnable interface

Source: Internet
Author: User

 Packageunit8;ImportJava.applet.Applet;ImportJava.awt.Label;ImportJava.awt.TextField; Public classTestrunnableextendsAppletImplementsrunnable{Label prompt1=NewLabel ("The first thread:"); Label Prompt2=NewLabel ("The second thread:"); TextField Threadfirst=NewTextField (28); TextField Threadsecond=NewTextField (28);    Thread thread1,thread2; intCount1=0,count2=0;  Public voidinit () {Add (PROMPT1);        Add (Threadfirst);        Add (PROMPT2);    Add (Threadsecond); }     Public voidstart () {//creates a thread object with the Run method of the current class and specifies the name of the thread object with a stringThread1 =NewThread ( This, "Firstthread"); Thread2=NewThread ( This, "Secondthread");        Thread1.start ();    Thread2.start (); }     Public voidrun () {String currentrunning;  while(true){            Try{Thread.Sleep (int) (Math.random () *3000)); }Catch(interruptedexception e) {//Todo:handle Exception} currentrunning=Thread.CurrentThread (). GetName (); if(Currentrunning.equals ("Firstthread") ) {Count1++; Threadfirst.settext ("Number of threads 1 calls:" +count1); }Else if(Currentrunning.equals ("Secondthread") ) {Count2++; Threadsecond.settext ("Number of Threads 2 calls:" +Count2); }        }    }}

By implementing the Runnable interface to implement the thread, implement the Run method, so that when the main program sleep, the child threads are executed, where the child threads are instance objects of the thread class.

Java Multithreading--Implement Runnable interface

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.