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()