Java Multithreading

本文详细介绍了Java中多线程的概念、生命周期、优先级及其实现方式。从Thread类实例到线程执行,再到主线程的特性,为读者提供了全面的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ref: http://www.studytonight.com/java/multithreading-in-java

Multithreading      

A program can be divided into a number of small processes. Each small process can be addressed as a single thread (a lightweight process). Multithreaded programs contain two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. For example, one thread is writing content on a file at the same time another thread is performing spelling check.

In Java, thread means two different things:

1. an instance of Thread 

2. a thread execution

 

An instance of Thread class is just an object, like any other object in java. But a thread of execution means an individual "lightweight" process that has its own call stack. In java each thread has its own call stack

 

The main thread

Even if you don't create any thread in your program, a thread called main thread is still created. Although the main thread is automatically created, you can control it by obtaining a reference to it by calling currentThread() method.

Two important things to know about main thread are,

  • It is the thread from which other threads will be produced.
  • main thread must be always the last thread to finish execution.
class MainThread
{
 public static void main(String[] args)
 {
  Thread t=Thread.currentThread();
  t.setName("MainThread");
  System.out.println("Name of thread is "+t);
 }
}

Output :
Name of thread is Thread[MainThread,5,main]

Life cycle of a Thread

 

  1. New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on it.
  2. Runable : After invocation of start() method on new thread, the thread becomes runable.
  3. Running : A method is in running thread if the thread scheduler has selected it.
  4. Waiting : A thread is waiting for another thread to perform a task. In this stage the thread is still alive.
  5. Terminated : A thread enter the terminated state when it complete its task

 

Thread Priorities

Every thread has a priority that helps the operating system determine the order in which threads are scheduled for execution. In java thread priority ranges between,

  • MIN-PRIORITY (a constant of 1)
  • MAX-PRIORITY (a constant of 10)

By default every thread is given a NORM-PRIORITY(5). The main thread always have NORM-PRIORITY.

 

 





 

转载于:https://www.cnblogs.com/morningdew/p/5618981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值