Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Experiment No. 46: Q. Write A Program For Creating Threads Using Thread Class. Program

The document contains code snippets from 61 programming experiments related to threads and concurrency in Java. The experiments cover concepts like creating threads using Thread class and Runnable interface, sleeping threads, naming threads, setting thread priority, creating daemon threads, using thread pools, multitasking with threads, anonymous classes, invoking garbage collector, using runtime classes, synchronization using synchronized methods and blocks, database connectivity using JDBC, and creating/inserting tables in MySQL database.

Uploaded by

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

Experiment No. 46: Q. Write A Program For Creating Threads Using Thread Class. Program

The document contains code snippets from 61 programming experiments related to threads and concurrency in Java. The experiments cover concepts like creating threads using Thread class and Runnable interface, sleeping threads, naming threads, setting thread priority, creating daemon threads, using thread pools, multitasking with threads, anonymous classes, invoking garbage collector, using runtime classes, synchronization using synchronized methods and blocks, database connectivity using JDBC, and creating/inserting tables in MySQL database.

Uploaded by

rishabh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Experiment No.

46

Q. Write a program for creating threads using Thread Class.


Program :
public class ThreadUsingThreadClass extends Thread{
public void run(){
System.out.println("thread running successfully");
}
public static void main(String[] args) {
ThreadUsingThreadClass t1=new ThreadUsingThreadClass();
t1.start();
}
}

Output:
Experiment No. 47

Q. Write a program for creating threads using Runnable Interface.


Program :
public class ThreadUsingRunningInterface implements Runnable{
public void run(){
System.out.println("thread running successfully");
}
public static void main(String[] args) {
ThreadUsingRunningInterface t1=new ThreadUsingRunningInterface();
Thread th=new Thread(t1);
th.start();
}
}

Output:
Experiment No. 48

Q. Write a program for sleeping a thread.


Program :
public class ThreadSleep extends Thread{
public void run(){
try{
Thread.sleep(5000);
}
catch(Exception e){}
System.out.println("thread running successfully");
}
public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep();

t1.start();

Output :
Experiment No. 49

Q. Write a program for naming the thread.


Program :
public class ThreadSleep extends Thread{
public void run(){
System.out.println(this.getName()+"\n thread running successfully");
}
public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep();
t1.setName("My Name is thread");
t1.start();

Output :
Experiment No. 50

Q. Write a program for running multiple threads according to Priority.


Program :
public class ThreadSleep extends Thread{
public void run(){

System.out.println(this.getName()+"\n thread running successfully");


}
public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep();
ThreadSleep t2=new ThreadSleep();

t1.setName("thread1");
t2.setName("thread2");
t1.setPriority(MIN_PRIORITY);
t2.setPriority(10);
t1.start();
t2.start();
}

Output :
Experiment No. 51

Q. Write a program for creating Daemon Thread.


Program :

public class ThreadSleep extends Thread{


public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep(){public void run(){
System.out.println(this.getName()+" is running now" );
try {
for(int i=0;i<5;i++)
{
System.out.println(i);
Thread.sleep(1000); }
} catch (Exception e) {
}
}
};
ThreadSleep t2=new ThreadSleep(){public void run(){
System.out.println(this.getName()+" is running now ");
try {
for(int i=100;i>95;i--)
{
System.out.println(i);
Thread.sleep(500);
} } catch (Exception e) {
}
}
};
t1.setDaemon(true); //creating daemon thread
t1.setName("thread1");
t2.setName("thread2");

t1.start();
t2.start();
}
}

Output :
Experiment No. 52

Q. Write a program showing implementation and working of Thread Pool.


Program :

import java.util.concurrent.*;
class ThreadpoolDemo implements Runnable{
String name;

public ThreadpoolDemo(String name) {


this.name = name;
}

public void run(){


System.out.println("initiating thread "+this.name);
System.out.println("hi"+ this.name);
System.out.println("shuting down "+this.name);
}
}
public class pool {
public static void main(String[] args) {
Runnable r1=new ThreadpoolDemo("Thread1");
Runnable r2=new ThreadpoolDemo("Thread2");
Runnable r3=new ThreadpoolDemo("Thread3");
Runnable r4=new ThreadpoolDemo("Thread4");
Runnable r5=new ThreadpoolDemo("Thread5");

ExecutorService pol=Executors.newFixedThreadPool(3);
pol.execute(r1);
pol.execute(r2);
pol.execute(r3);
pol.execute(r4);
pol.execute(r5);
pol.shutdown();
}
}
Output :
Experiment No. 53

Q. Write a program for multitasking using multithreading.


Program :
public class ThreadSleep extends Thread{
public void run(){
try {
for(int i=0;i<5;i++){
Thread.sleep(1000);
System.out.println(this.getName()+" running round "+ i );
}
} catch (Exception e) {
}

}
public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep();
ThreadSleep t2=new ThreadSleep();

t1.setName("thread1");
t2.setName("thread2");

t1.start();
t2.start();
}

Output :
Experiment No. 54

Q. Write a program for multitasking using Anonymous class.


Program :

public class ThreadSleep extends Thread{


public static void main(String[] args) {
ThreadSleep t1=new ThreadSleep(){public void run(){
System.out.println(this.getName()+" is running now" );
for(int i=0;i<5;i++)
System.out.println(i);
}};
ThreadSleep t2=new ThreadSleep(){public void run(){
System.out.println(this.getName()+" is running now ");
for(int i=100;i>95;i--)
System.out.println(i);
}
};

t1.setName("thread1");
t2.setName("thread2");

t1.start();
t2.start();
}

Output :
Experiment No. 55

Q. Write a program for Explicitly invoking Garbage Collector.


Program :

public class ThreadUsingRunningInterface implements Runnable{


public void run(){
System.out.println("thread running successfully");
}
public static void main(String[] args)throws Exception {
ThreadUsingRunningInterface t1=new ThreadUsingRunningInterface();
t1=null;
System.gc();
}

@Override
protected void finalize() throws Throwable {
System.out.println("Finalize started by Garbage Collector Explicitly by object of " + this
);
}

Output :
Experiment No. 56

Q. Write a program for implementing Runtime Classes.


Program :
public class RuntimeEx {
public static void main(String[] args) throws Exception{
Runtime.getRuntime().exec("notepad");
}

Output :
Experiment No. 57

Q. Write a program showing Synchronization using Synchronize method.


Program :

class rick{
synchronized void check(){
System.out.println("method locked by "+this);
for (int i = 0; i < 5; i++) {

System.out.println(i);
try {

Thread.sleep(1000);
} catch (Exception e) {
}

}
System.out.println("method unlocked by "+this);
}
}

class ThreadSleep2 extends Thread{


final rick r;

public ThreadSleep2(rick r) {
this.r = r;
}

public void run(){


r.check();
}
}
class ThreadSleep1 extends Thread{
final rick r;

public ThreadSleep1(rick r) {
this.r = r;
}

public void run(){


r.check();
}

}
public class ThreadSleep {

public static void main(String[] args) {


rick obj=new rick();
ThreadSleep1 t1=new ThreadSleep1(obj);
ThreadSleep2 t2=new ThreadSleep2(obj);
t1.start();
t2.start();
}
}

Output :
Experiment No. 58

Q. Write a program showing Synchronization using Synchronize block.


Program :

class rick{
void check(int k){
synchronized(this){
System.out.println("method locked by "+this);
for (int i = 0; i < k; i++) {

System.out.println(i);
try {

Thread.sleep(1000);
} catch (Exception e) {
}

}
System.out.println("method unlocked by "+this);
}
}
}

class ThreadSleep2 extends Thread{


final rick r;

public ThreadSleep2(rick r) {
this.r = r;
}

public void run(){


r.check(5);
}

class ThreadSleep1 extends Thread{


final rick r;

public ThreadSleep1(rick r) {
this.r = r;
}

public void run(){


r.check(3);
}
}
public class ThreadSleep {

public static void main(String[] args) {


rick obj=new rick();
ThreadSleep1 t1=new ThreadSleep1(obj);
ThreadSleep2 t2=new ThreadSleep2(obj);

t1.start();
t2.start();

Output :
Experiment No. 59

Q. Write a program showing Database Connectivity using java Jdbc Interface.


Program :
import java.sql.*;
public class JdbcOne {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/check",
"root","");
System.out.println("Connection created");
con.close();
System.out.println("Connection terminated");
} catch (Exception e) {
}
}

Output :
Experiment No. 60

Q. Write a program for creating table in Mysql using Java.


Program :

import java.sql.*;

public class JdbcDemo {


private static Connection con=null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/check", "root","");
Statement st=con.createStatement();
int rs=st.executeUpdate("create table java1(id INTEGER,name varchar(20),age
integer)");
System.out.println("Table created");
con.close();
} catch (Exception e) {
}
}
}

Output :
Experiment No. 61

Q. Write a program for inserting Data in table in Mysql using Java.


Program :

import java.sql.*;
public class JdbcDemo {
private static Connection con=null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/check", "root","");
Statement st=con.createStatement();
int rs=st.executeUpdate("insert into java2 values(1,'Karan',19)");
System.out.println("Data inserted");
con.close();
} catch (Exception e) {
}
}
}

Output :
Experiment No. 62

Q. Write a program to retrieve data from Mysql database using java


Program :

import java.sql.*;

public class JdbcDemo {


private static Connection con=null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/check", "root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from java2");
while(rs.next()){
System.out.println("Id : "+ rs.getInt("id")+"\t Name : " +rs.getString("name")+"\t
Age : "+rs.getInt("age"));
}
con.close();
} catch (Exception e) {
}
}
}

Output :
Experiment No. 63

Q. Write difference between Throw and Throws.


A. There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

Throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.

Checked exception cannot be propagated Checked exception can be propagated with


using throw only. throws
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions.

Experiment No. 64

Q. Write difference between AWT and JSwing .


A. There are many differences between java awt and swing that are given below.
Java AWT Java Swing
AWT components are platform-dependent. Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.
Experiment No. 65

Q. Write difference between JDBC 3.0 and JDBC 4.0.


A.
Experiment No. 66

Q. Explain Why we can’t implement every method of JDBC interface .


A.
Experiment No. 67

Q. Write a program creating Form using JSwings.


Program :

import java.sql.*;

public class Jframedemo extends javax.swing.JFrame {


private int id;
private String Name=null;
private int age;

public Jframedemo() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();


jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Name : ");

jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});

jLabel2.setText("Id : ");

jLabel3.setText("Age : ");

jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});

jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});

jButton1.setLabel("Save");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(86, 86, 86)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(jTextField1)
.addComponent(jTextField2)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE,
115, Short.MAX_VALUE))))
.addContainerGap(144, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(jButton1)
.addContainerGap(101, Short.MAX_VALUE))
);

jLabel1.getAccessibleContext().setAccessibleName("jlabel1");
jTextField1.getAccessibleContext().setAccessibleName("tf1");

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/check",
"root","");
System.out.println("Connection created");

PreparedStatement ps=con.prepareStatement("insert into java2 values(?,?,?)");


ps.setInt(1,Integer.parseInt(jTextField2.getText()));
ps.setString(2, jTextField1.getText());
ps.setInt(3, Integer.parseInt(jTextField3.getText()));
ps.executeUpdate();
con.close();
} catch (Exception e) {
}
}

public static void main(String args[]) {


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Jframedemo().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}

Output :
Experiment No. 68

Q. Write a program for implementation of AWT event handling.


Program :
import java.awt.*;
import java.awt.event.*;

public class AwtDemo extends Frame implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t2.setText(t1.getText());
}
else if(e.getSource()==b2)
{
t1.setText(" ");t2.setText(" ");
}
}
Button b1,b2;
TextField t1,t2;
public void initComponent()
{
setLayout(new FlowLayout());
b1=new Button("copy");
b2=new Button("clear");
t1=new TextField(10);
t2=new TextField(10);
add(t1);add(t2);
add(b1);add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
AwtDemo(){
initComponent();
}
public static void main(String args[])
{
AwtDemo ob=new AwtDemo();
ob.setSize(400,400);
ob.setVisible(true);
}
}

Output :

You might also like