Java Experiment 7-multithreaded programming

Source: Internet
Author: User

1 Creating Threads with Thread and Runnable

"Experimental Purpose"

(1) Understanding the implementation of the Runnable interface method to achieve multithreading.

(2) Mastering the setting of thread priority.

(3) Deepen the understanding of thread state transitions.

"Experimental Requirements"

Requirement one: Using multi-threading to realize rotating planets

Request two: Write a threadSyncdemo, design a method for itPublic class GetNumber ()from1Start counting to -stop. Where two synchronous threads are designedAthreadand theBthread, all withGetNumber ()Scramble for this -number. Note ThreadAthreadand theBthreadsynchronization control, which guarantees counting to -is stopped.


Requires two codes

Class Syncdemo implements Runnable {static int num = 1;public synchronized Boolean getnumber () throws Exception {THREAD.SL EEP, if (num <=) {System.out.println (Thread.CurrentThread (). GetName () + "" +num++); return true;} return false;} public void Run () {try {while (GetNumber ())} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} }}public class Fd {/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubsyncdemo Demo = new Syncdemo (); Thread athread = new Thread (demo, "A"); Thread bthread = new Thread (demo, "B"); Athread.start (); Bthread.start ();}}

Java Experiment 7-multithreaded programming

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.