Multithreading (multi-threading)

Source: Internet
Author: User

Creating Threads in Java

Things to does to the create threads in Java:

(1) Create a task (object)

Creating a task

public class Taskclass implements Runnable {

Public Taskclass () {...}

Implement the Run method in Runnable

  void Run () {

Things to does in the task}

}

Runnable interface

Public interface Runnable {

void run ();

}

(2) Create a thread and combine the task with the thread (object)

1 by

Create a task class

public class Taskclass implements Runnable {

Public Taskclass (...) { ... }

Implement the Run method in Runnable

void Run () {

Things to does in the task

}

}

public class threaddemo{

public void SomeMethod () {

Create an instance of Taskclass

Taskclass Task=new taskclass (...);

Create a thread

    Thread thread=new thread (Task);

Start a thread

    Thread.Start ();

}

}

 2 by

Custom Thread Class

public class Customthread extends Thread {

Public Customthread () {...}

Override the Run method in Runnable

void Run () {

Things to does in the task

}

}

public class threaddemo{

public void SomeMethod () {

Create a thread

Customthread thread1=new customthread ();

Start a thread

    Thread1.start ();

Create another thread

Customthread thread2=new Customthread ();

Start a thread

Thread2.start ();

}

  }

Main Thread

When a program starts, the main Thread automatically starts

The default name of the Thread:main with priority 5

public static void Main (string[] args) {

System.out.println ("Current thread:" + Thread.CurrentThread ());

    Thread.CurrentThread (). SetName ("MyThread");

System.out.println ("After name change:" + Thread.CurrentThread ());

}

Example: Create Threads

public class ThreadDemo1 {

public static void Main (string[] args) {

String hw= "do home Work";

String tv= "Watch TV";

DoSomething dohw= New dosomething (HW);

DoSomething Watchtv = new dosomething (TV);

}

}

  

public class DoSomething {

Private String Dowhat;

Public dosomething (String athing) {

This.dowhat = athing;

DoIt ();

}

public void DoIt () {

for (int i=0;i<5;i++)

System.out.println (dowhat+ ":" +i);

}

}

does not use multithreading

Create Threads (Solution 1)

public class ThreadDemo1 {

public static void Main (string[] args) {

DoSomething dohw= New DoSomething ("Do home Work");

DoSomething Watchtv = new DoSomething ("Watch TV");

Thread hwthread= new Thread (DOHW);

Thread tvthread = new Thread (WATCHTV);

      Hwthread.start ();

      Tvthread.start ();

}

}

public class DoSomething implements Runnable {

Private String Dowhat;

Public dosomething (String athing) {

This.dowhat = athing;

} public void Run () {

for (int i=0;i<5;i++)

System.out.println (dowhat+ ":" +i);

}

}

Create Threads Solution 2

public class ThreadDemo2 extends Thread {

String dothing;

ThreadDemo2 (String dowhat) {

This.dothing=dowhat;

}

public static void Main (string[] args) {

String hw= "do home Work";

String tv= "Watch TV";

    ThreadDemo2 thread1=new ThreadDemo2 (HW);

    ThreadDemo2 thread2=new THREADDEMO2 (TV);

    Thread1.start ();

    Thread2.start ();

}

  public void Run () {

    for (int i=0;i<5;i++)

      System.out.println (dothing+ ":" +i);

    }

  }

Control a Thread

public static void Yield ():

Causes the currently executing thread object to temporarily pause

Allow and threads to execute (execute)

    Athread.yield ();

T1.yield ();

T2.sleep (1000);

static void sleep (Long Millis):

Causes the currently executing thread to sleep (block) for the specified number of milliseconds

If the thread is blocked by sleep or wait, an interruptedexception is thrown

try {

Athread.sleep (1000);

Sleep for 1 second

} catch (Interruptedexception ex) {

Do sth ...

}

  Interrupt ():

Does not stop a thread Set ' interrupted ' status to true why interrupt?

  After interrupt are set, we can take actions

  Isinterrupted ():

Tests Whether this thread has been interrupted.

The interrupted status of the thread is unaffected by this method.

if (isinterrupted ()) {

Action

}

  Interrupted ():

  Tests whether the current thread has been interrupted.

The interrupted status of the thread is cleared by this method.

Returns:true if the current thread has been interrupted; False otherwise.

public class ThreadDemo2 extends Thread {

String dothing;

ThreadDemo2 (String dowhat) {

This.dothing=dowhat;

}

public static void Main (string[] args) {

String hw= "do home Work";

String tv= "Watch TV";

ThreadDemo2 thread1=new ThreadDemo2 (HW);

ThreadDemo2 thread2=new THREADDEMO2 (TV);

Thread1.start ();

Thread2.start ();

}

public void Run () {

for (int i=0;i<5;i++) {

System.out.println (dothing+ ":" +i);

      This.yield ();

}

}

}

public class ThreadDemo2 extends Thread {

String dothing;

ThreadDemo2 (String dowhat) {

This.dothing=dowhat;

}

public static void Main (string[] args) {

String hw= "do home Work";

String tv= "Watch TV";

ThreadDemo2 thread1=new ThreadDemo2 (HW);

ThreadDemo2 thread2=new THREADDEMO2 (TV);

Thread1.start ();

Thread2.start ();

}

public void Run () {

for (int i=0;i<5;i++) {

System.out.println (dothing+ ":" +i);

    try {

      This.sleep (10);

      } catch (Interruptedexception ex) {

      System.out.println ("sth wrong");

      }

}

}

}

Synchronization

Both or more threads share the same resource Synchronized method:

To make a method synchronized:add the Synchronized keyword to its declaration

When the one thread is executing a synchronized method for a object, all and threads that invoke synchronized methods for T He same object block (suspend execution) until the first thread is do with the object

End19

Multithreading (multi-threading)

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.