-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMultipleThread.java
More file actions
100 lines (76 loc) · 1.61 KB
/
Copy pathMultipleThread.java
File metadata and controls
100 lines (76 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//multithreading in java
//synchronizing multiple thread
import java.util.Scanner;
class Account
{
private int balance;
public Account(int balance )
{
this.balance = balance;
}
//checking balance
public boolean checkBalance(int w)
{
if(balance>w)
return true;
else
return false;
}
//withdrawl money
public void withdrawl(int a)
{
balance = balance -a;
System.out.println("Successfully withdrawl "+a);
System.out.println("Current balance is "+balance);
}
}
class Customer implements Runnable
{
private Account account;
private String name;
//constructor
public Customer(Account account,String name)
{
this.account = account;
this.name = name;
}
//overridding run function of Runnable interface
public void run()
{
Scanner sc = new Scanner(System.in);
//synchronizing thread
//this block will be access to one thread at a time
synchronized(account)
{
//taking input
System.out.println("Enter Amount to Withdrawl for "+name);
int ammount = sc.nextInt();
//checkBalance and withdrawl
if(account.checkBalance(ammount))
{
account.withdrawl(ammount);
System.out.println("Amount for "+name);
}
else
{
System.out.println("Insufficient Balance for"+name);
}
}
}
}
//main class
public class MultipleThread
{
public static void main(String []args)
{
//opening account
Account A = new Account(1000);
//account assigning to customer
Customer c1 = new Customer(A,"Ruby");
Customer c2 = new Customer(A,"python");
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
}
}