Thread:
Thread is the smallest unit of processing that can be performed in an Operating System(OS).Thread is the light weight process . Thread exists within a process , a process may contain multiple threads.
Multi-threading:
When multiple threads are running concurrently , this is known as multi-threading.
For Example:
Downloading a video song while playing video song at the same time. Multi-threading is also used in computer generated animation.
Widely used programming languages that allow developers to work on threads in their programs source code are Java , Python and .NET.
An example of threading how to set priority.
class Test extends Thread{
public Test(int a){
setPriority(a);
}
public void run(){
System.out.println(getName()+" "+getPriority());
}
}
public class Threading {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
// For MINIMUM_PRIORITY
Test t1= new Test(Thread.MIN_PRIORITY) ;
t1.start();
//For MAXIMUM_PRIORITY
Test t2= new Test(Thread.MAX_PRIORITY) ;
t2.start();
//For NORMAL_PRIORITY
Test t3= new Test(Thread.NORM_PRIORITY);
t3.start();
}
}
What is Synchronization ?
Process Synchronization means sharing system resources by processes in a such a way that , Concurrent access to shared data is handled there by minimizing the chance of inconsistent data . Maintaining data consistency demands mechanisms to ensure synchronized execution of cooperating processes
Code for Synchronization in Java
- public class SynchronizedAccountTesting implements Runnable {
- private Account acct = new Account();
- public static void main(String[] args) {
- SynchronizedAccountTesting r = new SynchronizedAccountTesting();
- Thread t1 = new Thread(r);
- Thread t2 = new Thread(r);
- t1.setName("ALi");
- t2.setName("Hamza");
- t1.start();
- t2.start();
- }
- public void run() {
- for (int i = 0; i < 5; i++) {
- makeWithdrawal(10);
- if (acct.getBalance() < 0) {
- System.out.println("account is overdrawn!");
- }
- }}
- private synchronized void makeWithdrawal(int amt) {
- if (acct.getBalance() >= amt ) {
- System.out.println(Thread.currentThread().getName() + " is going to withdrw");
- try {
- Thread.sleep(100);
- }
- catch (InterruptedException ex) {
- System.out.println(ex); }
- acct.withdraw(amt);
- System.out.println(Thread.currentThread().getName()+"completes the withdrawal");
- }
- else
- {
- System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance());
- }
- }
- }
- class Account {
- private int balance = 50;
- public int getBalance() {
- return balance;
- }
- public void withdraw(int amount) {
- balance = balance - amount;
- }}
Related Links:
source code for client server communication:
https://assignmentsppt.blogspot.com/2017/08/2way-client-server-communication-source.html
0 Comments