java 多线程(Multithreading in Java)

本文深入探讨了Java中多线程与多进程的优缺点,详细解释了为何多线程能节省内存和时间,提高程序效率。通过对比过程,揭示了线程间共享内存、轻量化特性和快速上下文切换的优势。

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

Multithreading in Java

1.we use multithreading than multiprocessing because threads use a shared memory area.They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

 

1) Process-based Multitasking (Multiprocessing)

  • Each process has an address in memory. In other words, each process allocates a separate memory area.
  • A process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

 Note: At a time one thread is executed only.

After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

 

  • Threads share the same address space.
  • A thread is lightweight.
  • Cost of communication between the thread is low.
  • estDaemonThread2 t1=new TestDaemonThread2();  
  •   TestDaemonThread2 t2=new TestDaemonThread2();  
  •   t1.start();  
  •   t1.setDaemon(true);//will throw exception here  

 如果一个线程已经启动,就不可以把它标记为deamon thread,否则会抛出IllegalThreadStateException

正确使用是先声明为守护线程,再start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值