0% found this document useful (0 votes)
27 views

Advanced Programming Laboratory

This document contains code examples demonstrating different threading concepts in Java, including join(), extending Thread, getting thread state, setting thread priority, and timed waiting states. It also includes code for a GUI application that calculates the area and perimeter of a circle based on user input radius.

Uploaded by

Lense Adugna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Advanced Programming Laboratory

This document contains code examples demonstrating different threading concepts in Java, including join(), extending Thread, getting thread state, setting thread priority, and timed waiting states. It also includes code for a GUI application that calculates the area and perimeter of a circle based on user input radius.

Uploaded by

Lense Adugna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter three (1)

Multithreading

Join example
1 package multithreadinng;
2 public class JoinExample1 extends Thread
3{
4 public void run()
5 {
6 for(int i=1; i<=4; i++)
7 {
8 try
9 {
10 Thread.sleep(500);
11 }catch(Exception e){System.out.println(e);}
12 System.out.println(i);
13 }
14 }
15 public static void main(String args[])
16 {
17 JoinExample1 thread1 = new JoinExample1();
18 JoinExample1 thread2 = new JoinExample1();
19 JoinExample1 thread3 = new JoinExample1();
20 thread1.start();
21 try
22 {
23 thread1.join();
24 }catch(Exception e){System.out.println(e);}
25 thread2.start();
26 thread3.start();
27 }
28 }
29
My Thread
package multithreadinng;
2 public class MyThread extends Thread{
3 @Override
4 public void run(){
5 System.out.println("Welcome to extended Threads");
6
7 }
8 public static void main(String[] args) {
9 System.out.println("Current Thread is: "+MyThread.currentThread());
10 MyThread mt = new MyThread();
11 mt.start();
12
13 }
14
15 }
16
17
New State
1 package multithreadinng;
2 public class NewState implements Runnable{
3 @Override
4 public void run(){
5 Thread.currentThread().getState();
6}
7 public static void main(String[] args) {
8 NewState ns = new NewState();
9 Thread t = new Thread(ns);
10 System.out.println("Thread State is:"+ t.getState());
11 }
12
13 }
Runnable State
1 package multithreadinng;
2
3 public class RunnableState implements Runnable {
4 @Override
5 public void run(){
6 System.out.println("Thread State is:"+ Thread.currentThread().getState());
7 }
8 public static void main(String[] args) {
9 RunnableState rs=new RunnableState();
10 Thread t=new Thread(rs);
11 t.start();
12 }
13
14 }
Thread priority

2 package multithreadinng;
3
4 public class ThreadPriority extends Thread {
5 @Override
6 public void run(){
7 System.out.println(Thread.currentThread().getName()+ "Priority is:" +
Thread.currentThread().getPriority());
8 }
9 public static void main(String[] args) {
10 ThreadPriority tp=new ThreadPriority();
11 ThreadPriority tp2=new ThreadPriority();
12
13 tp.setPriority(Thread.MIN_PRIORITY);
14 tp2.setPriority(Thread.MAX_PRIORITY);
15 tp.start();
16 tp2.start();
17 }
18
19 }
Timed waiting state
1 package multithreadinng;
2 public class TimedWaitingState implements Runnable{
3 @Override
4 public void run(){
5 try{
6 Thread.sleep(5000);
7 Thread.interrupted();
8 }
9 catch(InterruptedException e){
10 System.out.println(e);
11 }
12 }
13 public static void main(String[] args) throws InterruptedException {
14 TimedWaitingState tws = new TimedWaitingState();
15 Thread t1 = new Thread(tws);
16 t1.start();
17 Thread.sleep(1000);
18 System.out.println("Thread State is:"+t1.getState());
19 }
20 }
1 package multithreadinng;
2 import java.awt.Component;
3 import javax.swing.JOptionPane;
4 public class calculate_Area1 extends javax.swing.JFrame {
5
6 private Object output;
7 private double radius;
8
9 public calculate_Area1() {
10 initComponents();
11 }
12
13 @SuppressWarnings("unchecked")
14 // <editor-fold defaultstate="collapsed" desc="Generated Code">
15 private void initComponents() {
16
17 jPanel1 = new javax.swing.JPanel();
18 jLabel1 = new javax.swing.JLabel();
19 jPanel2 = new javax.swing.JPanel();
20 jLabel2 = new javax.swing.JLabel();
21 jLabel3 = new javax.swing.JLabel();
22 jLabel4 = new javax.swing.JLabel();
23 jPanel3 = new javax.swing.JPanel();
24 radiusTF = new javax.swing.JTextField();
25 areaTF = new javax.swing.JTextField();
26 perimeterTF = new javax.swing.JTextField();
27 jPanel4 = new javax.swing.JPanel();
28 computeBtn = new javax.swing.JButton();
29 clearBtn = new javax.swing.JButton();
30 exitBtn = new javax.swing.JButton();
31
32
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
33
34 jPanel1.setBackground(new java.awt.Color(204, 255, 255));
35
36 jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
37 jLabel1.setForeground(new java.awt.Color(51, 51, 255));
38 jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
39 jLabel1.setText("Calculate Area and Perimeter of Circle");
40
41 javax.swing.GroupLayout jPanel1Layout = new
javax.swing.GroupLayout(jPanel1);
42 jPanel1.setLayout(jPanel1Layout);
43 jPanel1Layout.setHorizontalGroup(
44
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
45 .addGroup(jPanel1Layout.createSequentialGroup()
46 .addGap(23, 23, 23)
47 .addComponent(jLabel1,
javax.swing.GroupLayout.PREFERRED_SIZE, 345,
javax.swing.GroupLayout.PREFERRED_SIZE)
48 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
49 );
50 jPanel1Layout.setVerticalGroup(
51
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
52 .addGroup(jPanel1Layout.createSequentialGroup()
53 .addContainerGap()
54 .addComponent(jLabel1)
55 .addContainerGap(20, Short.MAX_VALUE))
56 );
57
58 jPanel2.setBackground(new java.awt.Color(204, 255, 255));
59
60 jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
61 jLabel2.setText("Radius");
62
63 jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
64 jLabel3.setText("Perimeter");
65
66 jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
67 jLabel4.setText("Area");
68
69 javax.swing.GroupLayout jPanel2Layout = new
javax.swing.GroupLayout(jPanel2);
70 jPanel2.setLayout(jPanel2Layout);
71 jPanel2Layout.setHorizontalGroup(
72
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
73 .addGroup(jPanel2Layout.createSequentialGroup()
74 .addContainerGap()
75
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.L
EADING, false)
76 .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
77 .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
78 .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE,
71, Short.MAX_VALUE))
79 .addContainerGap(129, Short.MAX_VALUE))
80 );
81 jPanel2Layout.setVerticalGroup(
82
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
83 .addGroup(jPanel2Layout.createSequentialGroup()
84 .addContainerGap()
85 .addComponent(jLabel2,
javax.swing.GroupLayout.PREFERRED_SIZE, 25,
javax.swing.GroupLayout.PREFERRED_SIZE)
86 .addGap(18, 18, 18)
87 .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE,
26, Short.MAX_VALUE)
88 .addGap(33, 33, 33)
89 .addComponent(jLabel3,
javax.swing.GroupLayout.PREFERRED_SIZE, 26,
javax.swing.GroupLayout.PREFERRED_SIZE)
90 .addContainerGap())
91 );
92
93 jPanel3.setBackground(new java.awt.Color(204, 255, 255));
94
95 radiusTF.setFont(new java.awt.Font("Times New Roman", 1, 12)); //
NOI18N
96 radiusTF.setText("Enter your circle radius");
97 radiusTF.addFocusListener(new java.awt.event.FocusAdapter() {
98 public void focusGained(java.awt.event.FocusEvent evt) {
99 radiusTFFocusGained(evt);
100 }
101 public void focusLost(java.awt.event.FocusEvent evt) {
102 radiusTFFocusLost(evt);
103 }
104 });
105 radiusTF.addActionListener(new java.awt.event.ActionListener() {
106 public void actionPerformed(java.awt.event.ActionEvent evt) {
107 radiusTFActionPerformed(evt);
108 }
109 });
110 radiusTF.addKeyListener(new java.awt.event.KeyAdapter() {
111 public void keyTyped(java.awt.event.KeyEvent evt) {
112 radiusTFKeyTyped(evt);
113 }
114 });
115
116 areaTF.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
117 areaTF.setText("Computed area");
118 areaTF.addFocusListener(new java.awt.event.FocusAdapter() {
119 public void focusGained(java.awt.event.FocusEvent evt) {
120 areaTFFocusGained(evt);
121 }
122 public void focusLost(java.awt.event.FocusEvent evt) {
123 areaTFFocusLost(evt);
124 }
125 });
126 areaTF.addActionListener(new java.awt.event.ActionListener() {
127 public void actionPerformed(java.awt.event.ActionEvent evt) {
128 areaTFActionPerformed(evt);
129 }
130 });
131
132 perimeterTF.setFont(new java.awt.Font("Times New Roman", 1, 12)); //
NOI18N
133 perimeterTF.setText("Computed perimeter");
134 perimeterTF.addFocusListener(new java.awt.event.FocusAdapter() {
135 public void focusGained(java.awt.event.FocusEvent evt) {
136 perimeterTFFocusGained(evt);
137 }
138 public void focusLost(java.awt.event.FocusEvent evt) {
139 perimeterTFFocusLost(evt);
140 }
141 });
142 perimeterTF.addActionListener(new java.awt.event.ActionListener() {
143 public void actionPerformed(java.awt.event.ActionEvent evt) {
144 perimeterTFActionPerformed(evt);
145 }
146 });
147
148 javax.swing.GroupLayout jPanel3Layout = new
javax.swing.GroupLayout(jPanel3);
149 jPanel3.setLayout(jPanel3Layout);
150 jPanel3Layout.setHorizontalGroup(
151
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
152 .addComponent(radiusTF)
153 .addComponent(areaTF)
154 .addComponent(perimeterTF)
155 );
156 jPanel3Layout.setVerticalGroup(
157
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
158 .addGroup(jPanel3Layout.createSequentialGroup()
159 .addComponent(radiusTF,
javax.swing.GroupLayout.PREFERRED_SIZE, 31,
javax.swing.GroupLayout.PREFERRED_SIZE)
160 .addGap(27, 27, 27)
161 .addComponent(areaTF,
javax.swing.GroupLayout.PREFERRED_SIZE, 28,
javax.swing.GroupLayout.PREFERRED_SIZE)
162 .addGap(34, 34, 34)
163 .addComponent(perimeterTF))
164 );
165
166 jPanel4.setBackground(new java.awt.Color(204, 255, 255));
167
168 computeBtn.setFont(new java.awt.Font("Times New Roman", 1, 14)); //
NOI18N
169 computeBtn.setText("Compute");
170 computeBtn.addActionListener(new java.awt.event.ActionListener() {
171 public void actionPerformed(java.awt.event.ActionEvent evt) {
172 computeBtnActionPerformed(evt);
173 }
174 });
175
176 clearBtn.setFont(new java.awt.Font("Times New Roman", 1, 14)); //
NOI18N
177 clearBtn.setText("Clear");
178 clearBtn.addActionListener(new java.awt.event.ActionListener() {
179 public void actionPerformed(java.awt.event.ActionEvent evt) {
180 clearBtnActionPerformed(evt);
181 }
182 });
183
184 exitBtn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
185 exitBtn.setText("Exit");
186 exitBtn.addActionListener(new java.awt.event.ActionListener() {
187 public void actionPerformed(java.awt.event.ActionEvent evt) {
188 exitBtnActionPerformed(evt);
189 }
190 });
191
192 javax.swing.GroupLayout jPanel4Layout = new
javax.swing.GroupLayout(jPanel4);
193 jPanel4.setLayout(jPanel4Layout);
194 jPanel4Layout.setHorizontalGroup(
195
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
196 .addGroup(jPanel4Layout.createSequentialGroup()
197 .addContainerGap()
198 .addComponent(computeBtn)
199 .addGap(114, 114, 114)
200 .addComponent(clearBtn)
201 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.REL
ATED, 142, Short.MAX_VALUE)
202 .addComponent(exitBtn)
203 .addGap(43, 43, 43))
204 );
205 jPanel4Layout.setVerticalGroup(
206
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
207 .addGroup(jPanel4Layout.createSequentialGroup()
208 .addContainerGap(20, Short.MAX_VALUE)
209 .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayo
ut.Alignment.BASELINE)
210 .addComponent(computeBtn)
211 .addComponent(clearBtn)
212 .addComponent(exitBtn))
213 .addContainerGap())
214 );
215
216 javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
217 getContentPane().setLayout(layout);
218 layout.setHorizontalGroup(
219
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
220 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
221 .addGroup(layout.createSequentialGroup()
222 .addComponent(jPanel2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
223 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.REL
ATED)
224 .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
225 .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
226 );
227 layout.setVerticalGroup(
228
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
229 .addGroup(layout.createSequentialGroup()
230 .addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
231 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.REL
ATED)
232 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING, false)
233 .addComponent(jPanel2,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
234 .addComponent(jPanel3,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
235 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.REL
ATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
236 .addComponent(jPanel4,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
237 .addGap(0, 0, 0))
238 );
239
240 pack();
241 }// </editor-fold>
242
243 private void computeBtnActionPerformed(java.awt.event.ActionEvent evt) {
244 double radius = Double.parseDouble(radiusTF.getText());
245 final double PI = 3.14;
246 double area = radius*radius*PI;
247 areaTF.setText(Double.toString(area));
248 double perimeter = radius*PI*2;
249 perimeterTF.setText(Double.toString(perimeter));
250 // TODO add your handling code here:
251 }
252
253 private void exitBtnActionPerformed(java.awt.event.ActionEvent evt) {
254
255 if(JOptionPane.showConfirmDialog((Component) output,"Are you sure to
EXIT","EXIT",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_NO_OPTION)
256 {
257 System.exit(0);
258 }
259 // TODO add your handling code here:
260 }
261
262 private void clearBtnActionPerformed(java.awt.event.ActionEvent evt) {
263 radiusTF.setText(" ");
264 areaTF.setText(" ");
265 perimeterTF.setText(" ");
266 // TODO add your handling code here:
267 }
268
269 private void radiusTFActionPerformed(java.awt.event.ActionEvent evt) {
270
271 // TODO add your handling code here:
272 }
273
274 private void areaTFActionPerformed(java.awt.event.ActionEvent evt) {
275
276 // TODO add your handling code here:
277 }
278
279 private void perimeterTFFocusLost(java.awt.event.FocusEvent evt) {
280 if(perimeterTF.getText().equals(""))
281 {
282 perimeterTF.setText("Computed perimeter");
283 }
284 // TODO add your handling code here:
285 }
286
287 private void areaTFFocusLost(java.awt.event.FocusEvent evt) {
288 if(areaTF.getText().equals(""))
289 {
290 areaTF.setText("Computed area");
291 }
292 }
293
294 private void radiusTFFocusLost(java.awt.event.FocusEvent evt) {
295 if(radiusTF.getText().equals(""))
296 {
297 radiusTF.setText("Enter your circle radius");
298 }
299 // TODO add your handling code here:
300 }
301
302 private void radiusTFFocusGained(java.awt.event.FocusEvent evt) {
303 if(radiusTF.getText().equals("Enter your circle radius"))
304 {
305 radiusTF.setText("");
306 }
307 // TODO add your handling code here:
308 }
309
310 private void areaTFFocusGained(java.awt.event.FocusEvent evt) {
311 if(areaTF.getText().equals("Computed area"))
312 {
313 areaTF.setText("");
314 }
315 }
316
317 private void perimeterTFFocusGained(java.awt.event.FocusEvent evt) {
318 if(perimeterTF.getText().equals("Computed perimeter"))
319 {
320 perimeterTF.setText("");
321 }
322 }
323
324 private void perimeterTFActionPerformed(java.awt.event.ActionEvent evt)
{
325 // TODO add your handling code here:
326 }
327
328 private void radiusTFKeyTyped(java.awt.event.KeyEvent evt) {
329 char c = evt.getKeyChar();
330 if(!Character.isDigit(c)){
331 evt.consume();
332 radiusTF.setText("Enter only number");
333 }
334 }
335
336 public static void main(String args[]) {
337 /* Set the Nimbus look and feel */
338 //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
339 /* If Nimbus (introduced in Java SE 6) is not available, stay with the default
look and feel.
340 * For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
341 */
342 try {
343 for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
344 if ("Nimbus".equals(info.getName())) {
345 javax.swing.UIManager.setLookAndFeel(info.getClassName());
346 break;
347 }
348 }
349 } catch (ClassNotFoundException ex) {
350
java.util.logging.Logger.getLogger(calculate_Area1.class.getName()).log(java.util.log
ging.Level.SEVERE, null, ex);
351 } catch (InstantiationException ex) {
352
java.util.logging.Logger.getLogger(calculate_Area1.class.getName()).log(java.util.log
ging.Level.SEVERE, null, ex);
353 } catch (IllegalAccessException ex) {
354
java.util.logging.Logger.getLogger(calculate_Area1.class.getName()).log(java.util.log
ging.Level.SEVERE, null, ex);
355 } catch (javax.swing.UnsupportedLookAndFeelException ex) {
356
java.util.logging.Logger.getLogger(calculate_Area1.class.getName()).log(java.util.log
ging.Level.SEVERE, null, ex);
357 }
358 //</editor-fold>
359
360 /* Create and display the form */
361 java.awt.EventQueue.invokeLater(new Runnable() {
362 public void run() {
363 new calculate_Area1().setVisible(true);
364 }
365 });
366 }
367
368 // Variables declaration - do not modify
369 private javax.swing.JTextField areaTF;
370 private javax.swing.JButton clearBtn;
371 private javax.swing.JButton computeBtn;
372 private javax.swing.JButton exitBtn;
373 private javax.swing.JLabel jLabel1;
374 private javax.swing.JLabel jLabel2;
375 private javax.swing.JLabel jLabel3;
376 private javax.swing.JLabel jLabel4;
377 private javax.swing.JPanel jPanel1;
378 private javax.swing.JPanel jPanel2;
379 private javax.swing.JPanel jPanel3;
380 private javax.swing.JPanel jPanel4;
381 private javax.swing.JTextField perimeterTF;
382 private javax.swing.JTextField radiusTF;
383 // End of variables declaration
384
385 private static class component {
386
387 public component() {
388 }
389 }
390 }
Thread synchronization
With synchronization
1 package synchronization;
2 class Power{
3 synchronized void printPower(int n){//method synchronized
4 int temp = 1;
5 for(int i=1;i<=5;i++){
6 System.out.println(Thread.currentThread().getName() + ":- " +n + "^"+ i + "
value: " + n*temp);
7 temp = n*temp;
8 try{
9 Thread.sleep(500);
10 }catch(Exception e){System.out.println(e);}
11 }
12 }
13 }
14 class Thread1 extends Thread{
15 Power p;
16 Thread1(Power p){
17 this.p=p;
18 }
19 public void run(){
20 p.printPower(5);
21 }
22 }
23 class Thread2 extends Thread{
24 Power p;
25 Thread2(Power p){
26 this.p=p;
27 }
28 public void run(){
29 p.printPower(8);
30 }
31 }
32 public class Synchronization_withsynchronization{
33 public static void main(String args[]){
34 Power obj = new Power();//only one object
35 Thread1 p1=new Thread1(obj);
36 Thread2 p2=new Thread2(obj);
37 p1.start();
38 p2.start();
39 }
40 }
41

Producer consumer with synchronization

1 package synchronization;
2
3 import java.util.concurrent.BlockingQueue;
4 import java.util.concurrent.LinkedBlockingQueue;
5
6 public class ProducerConsumerwithsync{
7
8 public static void main(String[] args) {
9 BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
10 //create producer threads
11 Thread producer = new Thread(() -> {
12 for (int i = 0; i < 10; i++) {
13 try {
14 queue.put(i);
15 System.out.println("Produced: " + i);
16 } catch (InterruptedException e) {
17 e.printStackTrace();
18 }
19 }
20 });
21 //create consumer threads
22 Thread consumer = new Thread(() -> {
23 for (int i = 0; i < 10; i++) {
24 try {
25 int value = queue.take();
26 System.out.println("Consumed: " + value);
27 } catch (InterruptedException e) {
28 e.printStackTrace();
29 }
30 }
31 });
32 //start the threads
33 producer.start();
34 consumer.start();
35 //code that may throw an exeption
36 try {
37 producer.join();
38 consumer.join();
39 }
40 //handle the exeption
41 catch (InterruptedException e) {
42 e.printStackTrace();
43 }
44 }
45 }
Producer consumer without synchronization
package multithreadinng;
3
4 import java.util.concurrent.Semaphore;
5 public class ProducerConsumerwhithout {
6 private static final int BUFFER_SIZE = 10;
7 private static final Semaphore mutex = new Semaphore(1);
8 private static final Semaphore empty = new Semaphore(BUFFER_SIZE);
9 private static final Semaphore full = new Semaphore(0);
10 private static final int[] buffer = new int[BUFFER_SIZE];
11 private static int count = 0;
12
13 public static void main(String[] args) {
14 Thread producer = new Thread(() -> {
15 for (int i = 0; i < 100; i++) {
16 try {
17 empty.acquire();
18 mutex.acquire();
19 buffer[count] = i;
20 count++;
21 System.out.println("Produced: " + i);
22 mutex.release();
23 full.release();
24 } catch (InterruptedException e) {
25 e.printStackTrace();
26 }
27 }
28 });
29
30 Thread consumer = new Thread(() -> {
31 for (int i = 0; i < 100; i++) {
32 try {
33 full.acquire();
34 mutex.acquire();
35 count--;
36 System.out.println("Consumed: " + buffer[count]);
37 mutex.release();
38 empty.release();
39 } catch (InterruptedException e) {
40 e.printStackTrace();
41 }
42 }
43 });
44
45 producer.start();
46 consumer.start();
47 }
48 }

Chapter three (2)


Networking

Manipulate Web File


1 package networking;
2 import java.awt.BorderLayout;
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import java.io.IOException;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.util.Scanner;
9 import java.util.logging.Level;
10 import java.util.logging.Logger;
11 import javax.swing.JButton;
12 import javax.swing.JFrame;
13 import javax.swing.JLabel;
14 import javax.swing.JPanel;
15 import javax.swing.JScrollPane;
16 import javax.swing.JTextArea;
17 import javax.swing.JTextField;
18 public class ManipulateWebFile extends JFrame {
19 private final JButton btn = new JButton ("View");
20 private final JTextField txtField = new JTextField(12);
21 private final JTextArea txtArea = new JTextArea();
22 private final JLabel Label = new JLabel();
23 public ManipulateWebFile(){
24 JPanel Panel = new JPanel();
25 Panel.setLayout(new BorderLayout());
26 Panel.add(new JLabel("Filename"),BorderLayout.WEST);
27 Panel.add(txtField, BorderLayout.CENTER);
28 Panel.add(btn, BorderLayout.EAST);
29 setLayout(new BorderLayout());
30 add(new JScrollPane(txtArea),BorderLayout.CENTER);
31 add(Panel, BorderLayout.NORTH);
32 add(Label, BorderLayout.SOUTH);
33 btn.addActionListener(new ActionListener () {
34 @Override
35 public void actionPerformed(ActionEvent e) {
36 try {
37 showFile();
38 } catch (IOException ex) {
39
Logger.getLogger(ManipulateWebFile.class.getName()).log(Level.SEVERE, null,
ex);
40 }
41 }
42 private void showFile() throws IOException {
43 Scanner input = null;
44 URL url = null;
45 try {
46 url = new URL(txtField.getText().trim());
47 input = new Scanner (url.openStream());
48 while (input.hasNext()){
49 txtArea.append(input.nextLine() + "\n");
50 }
51 Label.setText("File loaded successfully!");
52 } catch (MalformedURLException ex) {
53 Label.setText("URL" + url + "not FOUND &"+ex);
54
Logger.getLogger(ManipulateWebFile.class.getName()).log(Level.SEVERE, null,
ex);
55 }
56 catch(IOException exc){
57 Label.setText("URL" + url + "not FOUND" + exc);
58 }
59 finally {
60 if(input != null){
61 input.close();
62 }
63 }
64
65
66 }
67 });
68
69 }
70
71 public static void main(String[] args) {
72 ManipulateWebFile mwf = new ManipulateWebFile();
73 mwf.setTitle("Manipulate File on Web Server");
74 mwf.setSize(600, 250);
75 mwf.setLocationRelativeTo(null);
76 mwf.setVisible(true);
77 mwf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
78
79 // TODO code application logic here
80 }
81 }
82

Circle area Servers


package networking;
2 import java.io.DataInputStream;
3 import java.io.DataOutputStream;
4 import java.io.IOException;
5 import java.net.ServerSocket;
6 import java.net.Socket;
7 public class CircleAreaServer {
8 public static void main(String[] args) throws IOException{
9 ServerSocket server = new ServerSocket(8000, 50);
10 System.out.println("@-Server started-@");
11 Socket socket = server.accept();
12 DataInputStream in = new DataInputStream(socket.getInputStream());
13 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
14 double radius = Double.parseDouble(in.readUTF());
15 System.out.println("\tEntered radius is: "+radius);
16 double area = Math.ceil(Math.PI*Math.pow(radius, 2));
17 out.writeUTF(String.valueOf(area));
18 System.out.println("\tComputed Area of circle is: " +area);
19 out.close();
20 in.close();
21 socket.close();
22 server.close();
23 }
24
25 }
26
Circle area clients
package networking;
2
3 import java.io.BufferedReader;
4 import java.io.DataInputStream;
5 import java.io.DataOutputStream;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.net.Socket;
9
10 public class CircleAreaClient {
11 public static void main(String[] args) throws IOException{
12 Socket socket = new Socket("localhost",8000);
13 System.out.println("@-client started-@");
14 DataInputStream in = new DataInputStream (socket.getInputStream());
15 DataOutputStream out = new DataOutputStream (socket.getOutputStream());
16 BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
17 String radius;
18 System.out.print("\t Enter Radius: ");
19 radius = br.readLine();
20 out.writeUTF(radius);
21 String area = in.readUTF();
22 System.out.print("\t Recieved area of circle is: "+area);
23 in.close();
24 out.close();
25 socket.close();
26
27 }
28
29 }
30
Datagram Clients
1 package networking;
2
3 import java.net.DatagramPacket;
4 import java.net.DatagramSocket;
5 import java.net.InetAddress;
6
7 public class DatagramClient {
8 public static void main(String[] args)throws Exception {
9 DatagramSocket client = new DatagramSocket();
10 InetAddress address = InetAddress.getByName("localhost");
11 System.out.println(" @-UDP Client Started-@ ");
12 double radius = 5;
13 String area = String.valueOf(Math.ceil((Math.PI*Math.pow(radius,2))));
14 byte[] circle = area.getBytes();
15 DatagramPacket packet = new DatagramPacket(circle,
circle.length,address,4160);
16 client.send(packet);
17 System.out.println("Recieved Circle Area is: "+area);
18 client.close();
19 }
20
21 }
22

Datagram Servers
1 package networking;
2
3 import com.sun.xml.internal.ws.api.message.Packet;
4 import java.net.DatagramPacket;
5 import java.net.DatagramSocket;
6 import java.net.SocketException;
7 import javafx.scene.shape.Circle;
8 public class DatagramServer {
9 public static void main(String[] args) throws Exception {
10 DatagramSocket server = new DatagramSocket(4260);
11 System.out.println("UDP @-Server Started-@ ");
12 byte[] circle = new byte[256];
13 DatagramPacket packet = new DatagramPacket(circle, circle.length);
14 server.receive(packet);
15 String response = new String(packet.getData());
16 System.out.println("Computed circle area is: "+response);
17 server.close();
18
19 }
20
21 }
22

Chapter three (3)

Employee Lab
package JDBC;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 public class MyJDBC {
10
11 public static void main(String[] args) throws ClassNotFoundException,
SQLException {
12 Class.forName("com.mysql.jdbc.Driver");
13
14 String url = "jdbc:mysql://localhost:3306/javabook";
15 String user = "java";
16 String password = "root";
17 Connection connect = DriverManager.getConnection(url, user, password);
18
19 Statement stmt = connect.createStatement();
20 stmt.executeUpdate("create table IF NOT EXISTS Employee(Number int
primary key, Name varchar(50), Department varchar(50), Salary double)");
21 ResultSet rst = stmt.executeQuery("select * from Employee");
22 System.out.println("Number\tName\tDepartment\tSalary");
23 while (rst.next()){
24 System.out.println(rst.getInt(1) + "\t"+rst.getString(2) + "\
t"+rst.getString(3) + "\t"+rst.getDouble(4));
25 }
26 }
27
28 }
29

Course JDBC
1 package JDBC;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 public class CourseJDBC {
10 public static void main(String[] args)throws ClassNotFoundException,
SQLException {
11 Class.forName("com.mysql.jdbc.Driver");
12
13 String url = "jdbc:mysql://localhost:3306/javabook";
14 String user = "java";
15 String password = "root";
16 Connection connect = DriverManager.getConnection(url, user, password);
17
18 Statement stmt = connect.createStatement();
19 stmt.executeUpdate("create table IF NOT EXISTS course(Number int
PRIMARY KEY, Coursename varchar (60), Coursecredit int,Coursecode varchar
(60))");
20 ResultSet rst = stmt.executeQuery("select * from Course");
21 System.out.println("Number\tCoursename\tCoursecredit\tCoursecode");
22 while (rst.next()){
23 System.out.println(rst.getInt(1) + "\t"+rst.getString(2) + "\t"+rst.getInt(3) +
"\t"+rst.getString(4));
24 }
25
26
27 }
28
29 }
30

You might also like