Tuesday, November 16, 2010

Hibernate Full Web Application in NetBeans

New->Hibernate Mapping Wizard(This file should in default package)

Select->MySQL Wizard->Finish(Click on finish button)


Double click on Hibernate.cfg.xml->click on XML tab(View like this)
then add mapping class in to this XML(last section in XML file)



After this add Hibernate mapping wizard


















set Hibernate mapping wizard as Users.hbm

















class to map :com.Users(package_name.class_name)
select configure file:hibernate.cfg.xml
database table:Users(table_name)

Then click on xml view for Users.hbm add those steps
















ADD Java file( Users.java)

package com;


public class Users {

private int id;
private String user;
private String pass;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getPass() {
return pass;
}

public void setPass(String pass) {
this.pass = pass;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}
}


Then create Table

create table users
(
userid int auto_increment primary key,
user_name varchar(40),
pasword varchar(40)
)


Then Create servlet file(saveUser.java)

















import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;


public class saveUser extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

String user=request.getParameter("userName");
String pass=request.getParameter("passName");
Users Objectuser = new Users();

Objectuser.setUser(user);
Objectuser.setPass(pass);

try
{
Transaction tx=null;

SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();

Session session = sf.openSession();

tx=session.beginTransaction();
session.save(Objectuser);
session.getTransaction().commit();
session.close();
out.println("Inserted");
}
catch (Exception e) {
System.out.println("Error :"+e.getMessage());
out.println("Error :"+e.getMessage());
}
}
}

Finally create JSP Page




Saturday, February 6, 2010

Jasper Reports(Reports in Java)for Java Developers in netbeans


Embedding SQL Queries into a Report Template save as customerReport1.jrxml
(put into src/reports directories)
(Please send your feedback)












Add libraries files in Net-beans

  • jasperreports-3.1.3.jar
  • commons-beanutils-1.7.jar
  • commons-collections-2.1v
  • commons-digester-1.7.jar

Finally run this program

JasperView.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Gowthaman
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
public class JasperView {
Connection connection;
public void generateReport() throws FileNotFoundException, IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection ("Jdbc:mysql://localhost/samples", "root", "password");
System.out.println("Connected to the database");
System.out.println("Filling reports...");

JasperReport jasperReport;
JasperPrint jasperPrint;
jasperReport=JasperCompileManager.compileReport("src/reports/customerReport1.jrxml");
jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(),connection);
JasperExportManager.exportReportToPdfFile(jasperPrint, "src/reports/ProvaReport.pdf");
//automatically will created if you want PDF add library itext.jar
String reportDest = "src/reports/report.html";//automatically will created
JasperViewer jv = new JasperViewer(jasperPrint);
jv.setVisible(true);
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDest);
System.out.println("Done!Html and PDF");
connection.close();
}
catch (JRException e)
{
e.printStackTrace();
System.out.println("Jasper Exception:"+e.getMessage());
System.out.println("Jasper Exception:"+e.getStackTrace());
System.out.println("Jasper Exception:"+e.getLocalizedMessage());
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("There is exception here"+ e);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
new JasperView().generateReport();
}

}


Database Table

create table employee(
firstname varchar(40),
lastname varchar(40)
)

Wednesday, December 30, 2009

Hibernate Web Application in NetBeans





New->Hibernate Mapping Wizard(This file should in default package)

Select->MySQL Wizard->Finish(Click on finish button)


Double click on Hibernate.cfg.xml->click on XML tab(View like this)
then add mapping class in to this XML(last section in XML file)



Add->Java file ( into default package)

InsertUser.java

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;

/**
*
* @author Gowthaman
*/
@Entity
@Table(name = "User", catalog = "Users")
public class InsertUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
// @GeneratedValue(strategy = GenerationType.AUTO)


@Column(name="user")
private String user;

@Column(name="password")
private String pass;


public void setUser(String user){
this.user=user;
}

public void setPass(String pass){
this.pass=pass;
}
}

This file map to hibernate that is called Annotation

create Database in MYSQL

schema as Users


create table user
(
user Varchar(25),
password Varchar(25)

);


Create anther Java file for insert data into database

New->Java File(add into default package)
AddUser.java

import javax.servlet.*;
import javax.servlet.http.*;
public class AddUser extends HttpServlet{

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
String user = request.getParameter("user").toString();
String pass = request.getParameter("pass").toString();

SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();

Session s1 = sf.openSession();

InsertUser cs=new InsertUser();//create object for InsertUser.java

cs.setUser(user);
cs.setPass(pass);

s1.beginTransaction();
s1.save(cs);
s1.getTransaction().commit();
s1.close();
sf.close();

out.println("

" + insert successfully + "

");
}

catch (Exception e) {
e.printStackTrace();
out.println("error:- "+e.getMessage());

}
}
}


web.xml(edit XML file in web-inf folder add the code last section


index.jsp


Monday, June 29, 2009

AbstractDemo

abstract class A3{
abstract void search();
//no body of statements in abstract method


void print(){
System.out.println("Non Abstract Method");
}
}

class B3 extends A3{
void search(){
System.out.println("Binary Search");
System.out.println("Linear Search");
}
}

class AbstractDemo{
public static void main(String[] a){
B3 b2=new B3();
b2.search();
b2.print();

A3 a2;
B3 b3=new B3();
a2=b3;
a2.print();
}
}

SimpleAboutDialog

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SimpleAboutDialog extends JDialog {
public SimpleAboutDialog(JFrame parent) {
super(parent, "About Dialog", true);

Box b = Box.createVerticalBox();
b.add(Box.createGlue());
b.add(new JLabel("Java source code, product and article"));
b.add(new JLabel("By Java source and support"));
b.add(new JLabel("At www.java2s.com"));
b.add(Box.createGlue());
getContentPane().add(b, "Center");

JPanel p2 = new JPanel();
JButton ok = new JButton("Ok");
p2.add(ok);
getContentPane().add(p2, "South");

ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});

setSize(250, 150);
}

public static void main(String[] args) {
JDialog f = new SimpleAboutDialog(new JFrame());
f.show();
}
}

FramewithComponents

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class FramewithComponents extends JFrame {
public FramewithComponents() {
super("JLayeredPane Demo");
setSize(256, 256);

JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.setOpaque(false);

JLabel label1 = new JLabel("Username:");
label1.setForeground(Color.white);
content.add(label1);

JTextField field = new JTextField(15);
content.add(field);

JLabel label2 = new JLabel("Password:");
label2.setForeground(Color.white);
content.add(label2);

JPasswordField fieldPass = new JPasswordField(15);
content.add(fieldPass);

getContentPane().setLayout(new FlowLayout());
getContentPane().add(content);
((JPanel) getContentPane()).setOpaque(false);

ImageIcon earth = new ImageIcon("1.jpg");
JLabel backlabel = new JLabel(earth);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0, 0, earth.getIconWidth(), earth.getIconHeight());

WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);

setVisible(true);
}

public static void main(String[] args) {
new FramewithComponents();
}
}

CenteredFrame

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class CenteredFrame extends JFrame {
public CenteredFrame() {
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
}

public static void main(String[] args) {
JFrame frame = new CenteredFrame();
frame.show();
}
}

Errordialogs

import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Errordialogs extends JPanel {

public static void main(String[] a) {

JOptionPane jop = new JOptionPane();
JOptionPane.showMessageDialog(jop, "Press Ok to exit our " +
"from the error diaolag box");
JOptionPane.showConfirmDialog(null, "Click one",
"Click one", JOptionPane.YES_NO_OPTION);

}
}

SimpleScreenManager

import java.awt.*;
import javax.swing.JFrame;

/**
The SimpleScreenManager class manages initializing and
displaying full screen graphics modes.
*/
public class SimpleScreenManager {

private GraphicsDevice device;

/**
Creates a new SimpleScreenManager object.
*/
public SimpleScreenManager() {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
device = environment.getDefaultScreenDevice();
}


/**
Enters full screen mode and changes the display mode.
*/
public void setFullScreen(DisplayMode displayMode,
JFrame window)
{
window.setUndecorated(true);
window.setResizable(false);

device.setFullScreenWindow(window);
if (displayMode != null &&
device.isDisplayChangeSupported())
{
try {
device.setDisplayMode(displayMode);
}
catch (IllegalArgumentException ex) {
// ignore - illegal mode for this device
}
}
}


/**
Returns the window currently used in full screen mode.
*/
public Window getFullScreenWindow() {
return device.getFullScreenWindow();
}


/**
Restores the screen's display mode.
*/
public void restoreScreen() {
Window window = device.getFullScreenWindow();
if (window != null) {
window.dispose();
}
device.setFullScreenWindow(null);
}

}

FullScreenTest

import java.awt.*;
import javax.swing.JFrame;

public class FullScreenTest extends JFrame {

public static void main(String[] args) {

DisplayMode displayMode;

if (args.length == 3) {
displayMode = new DisplayMode(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
DisplayMode.REFRESH_RATE_UNKNOWN);
}
else {
displayMode = new DisplayMode(800, 600, 16,
DisplayMode.REFRESH_RATE_UNKNOWN);
}

FullScreenTest test = new FullScreenTest();
test.run(displayMode);
}

private static final long DEMO_TIME = 5000;


public void run(DisplayMode displayMode) {
setBackground(Color.blue);
setForeground(Color.white);
setFont(new Font("Dialog", Font.PLAIN, 24));

SimpleScreenManager screen = new SimpleScreenManager();
try {
screen.setFullScreen(displayMode, this);
try {
Thread.sleep(DEMO_TIME);
}
catch (InterruptedException ex) { }
}
finally {
screen.restoreScreen();
}
}


public void paint(Graphics g) {
g.drawString("Hello World!", 20, 50);
}
}


java FullScreenTest 400 500 100

ImagePanel

public class ImagePanel extends JPanel {
private Image img;

public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null),
img.getHeight(null));
setSize(size);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setLayout(null);
}

}

Tuesday, June 9, 2009

Sample Login And Validation

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Login extends JFrame implements ActionListener
{
public JTextField t1;
public TextField t2;
public JLabel l1,l2,l3;
public JButton b1,b2;
public JPanel panel;
public Font g;

public Login()
{
g=new Font("",Font.BOLD,18);
getContentPane().setBackground(Color.magenta);
panel=(JPanel)getContentPane();
panel.setLayout(null);
l1=new JLabel("LOGIN FORM");

l2=new JLabel("LOGIN");
l3=new JLabel("PASSWORD");
t1=new JTextField(20);
t2=new TextField(20);
t2.setEchoChar('*');
b1=new JButton("OK");
b2=new JButton("EXIT");

panel.add(l1);
l1.setFont(g);
panel.add(l2);
panel.add(l3);

panel.add(t1);
panel.add(t2);
panel.add(b1);
panel.add(b2);


l1.setBounds(100,5,150,40);
l2.setBounds(30,60,100,30);
l3.setBounds(30,110,100,30);

t1.setBounds(140,60,150,30);
t2.setBounds(140,110,150,30);

b1.setBounds(140,180,60,30);
b2.setBounds(220,180,65,30);

t1.addActionListener(this);
t2.addActionListener(this);

b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String s1="mrp";
String s2="pandey";
String s3="OK";
String s4="EXIT";
String str=a.getActionCommand();

if(s3.equals(str))
{
if(s1.equals(t1.getText()) && s2.equals(t2.getText()))
{
this.dispose();
menu p=new menu();
p.setVisible(true);
p.setSize(800,700);
p.show();
this.dispose();
}
else
{
if(s3.equals(str))
{
t1.setText("");
t2.setText("");
JOptionPane.showMessageDialog(null,"Please varify the correct Login and Password","Warning",JOptionPane.OK_CANCEL_OPTION);
}
}
}

if( str=="EXIT")
{
JOptionPane.showMessageDialog(null,"The project is still in progress,do u want to quit now","Warning",JOptionPane.OK_CANCEL_OPTION);
if(s4.equals(str))
{
System.exit(0);
}
repaint();
}

}
public static void main(String args[])
{
Login f=new Login();
f.setVisible(true);
f.setSize(800,600);
f.show();
}

}

Multiple Interface

interface A {
}

interface B {
}

class X implements A, B {
}

class Y implements A {
B makeB() {
// Anonymous inner class:
return new B() {
};
}
}

public class MultiInterfaces {
static void takesA(A a) {
}

static void takesB(B b) {
}

public static void main(String[] args) {
X x = new X();
Y y = new Y();
takesA(x);
takesA(y);
takesB(x);
takesB(y.makeB());
}
} ///:~

Interface Inherit

/** Find out whether interfaces are inherited.
* Start with Thread which implements Runnable.
*/
public class InterfaceInherit extends Thread {
public static void main(String[] a) {
new InterfaceInherit().start();
}
public void run() {
if (this instanceof InterfaceInherit)
System.out.println("This is InterfaceInherit");
if (this instanceof Thread)
System.out.println("This is Thread");
if (this instanceof Runnable)
System.out.println("This is Thread -- Interfaces ARE inherited!");
}
}

Interface

interface I1 {

void methodI1(); // public static by default
}

interface I2 extends I1 {

void methodI2(); // public static by default
}

class A1 {

public String methodA1() {
String strA1 = "I am in methodC1 of class A1";
return strA1;
}
public String toString() {
return "toString() method of class A1";
}
}

class B1 extends A1 implements I2 {

public void methodI1() {
System.out.println("I am in methodI1 of class B1");
}
public void methodI2() {
System.out.println("I am in methodI2 of class B1");
}
}

class C1 implements I2 {

public void methodI1() {
System.out.println("I am in methodI1 of class C1");
}
public void methodI2() {
System.out.println("I am in methodI2 of class C1");
}
}


abstract class D1 implements I2 {

public void methodI1() {
}

}

public class InterFaceEx {

public static void main(String[] args) {
I1 i1 = new B1();
i1.methodI1();
((I2) i1).methodI2();
I2 i2 = new B1();
i2.methodI1();
i2.methodI2();


String var2 = ((A1) i1).methodA1();
System.out.println("var2 : " + var2);
String var3 = ((B1) i1).methodA1();
System.out.println("var3 : " + var3);
String var4 = i1.toString();
System.out.println("var4 : " + var4);
String var5 = i2.toString();
System.out.println("var5 : " + var5);
I1 i3 = new C1();
String var6 = i3.toString();
System.out.println("var6 : " + var6);
Object o1 = new B1();

((I1) o1).methodI1();
((I2) o1).methodI1();
((B1) o1).methodI1();

}
}

Thread Pool

public class ThreadPoolTest {

public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Tests the ThreadPool task.");
System.out.println(
"Usage: java ThreadPoolTest numTasks numThreads");
System.out.println( " numTasks - integer: number of task to run.");
System.out.println( " numThreads - integer: number of threads " +
"in the thread pool.");
return;
}
int numTasks = Integer.parseInt(args[0]);
int numThreads = Integer.parseInt(args[1]);

// create the thread pool
ThreadPool threadPool = new ThreadPool(numThreads);

// run example tasks
for (int i=0; i<numTasks; i++) {
threadPool.runTask(createTask(i));
}

// close the pool and wait for all tasks to finish.
threadPool.join();
}


/**
Creates a simple Runnable that prints an ID, waits 500
milliseconds, then prints the ID again.
*/
private static Runnable createTask(final int taskID) {
return new Runnable() {
public void run() {
System.out.println("Task " + taskID + ": start");

// simulate a long-running task
try {
Thread.sleep(500);
}
catch (InterruptedException ex) { }

System.out.println("Task " + taskID + ": end");
}
};
}
}







import java.util.LinkedList;

/**
A thread pool is a group of a limited number of threads that
are used to execute tasks.
*/
public class ThreadPool extends ThreadGroup {

private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;

/**
Creates a new ThreadPool.
@param numThreads The number of threads in the pool.
*/
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);

isAlive = true;

taskQueue = new LinkedList();
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
}


/**
Requests a new task to run. This method returns
immediately, and the task executes on the next available
idle thread in this ThreadPool.

Tasks start execution in the order they are received.
@param task The task to run. If null, no action is taken.
@throws IllegalStateException if this ThreadPool is
already closed.
*/
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}

}


protected synchronized Runnable getTask()
throws InterruptedException
{
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
}


/**
Closes this ThreadPool and returns immediately. All
threads are stopped, and any waiting tasks are not
executed. Once a ThreadPool is closed, no more tasks can
be run on this ThreadPool.
*/
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}


/**
Closes this ThreadPool and waits for all running threads
to finish. Any waiting tasks are executed.
*/
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}

// wait for all threads to finish
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i=0; i<count; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) { }
}
}


/**
A PooledThread is a Thread in a ThreadPool group,
designed to run tasks (Runnables).
*/
private class PooledThread extends Thread {


public PooledThread() {
super(ThreadPool.this,
"PooledThread-" + (threadID++));
}


public void run() {
while (!isInterrupted()) {

// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }

// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}

// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}


Run As : java ThreadPoolTest 5 2

Thread State

class ThreadStateDemo extends Thread{

Thread obj;
public static void main(String a[]){


new ThreadStateDemo();
}
ThreadStateDemo(){
obj=new Thread(this);

System.out.println("Thread obj is born");
System.out.println("Thread obj is ready");

obj.start();
}

public void run(){

System.out.println("THread obj is running");
}
}

Thread All Methods

class ChopStick{

boolean available;

ChopStick(){

available=true;
}

public synchronized void takeup(){

while(!available){
try
{
System.out.println("Hello is waiting for the other chopStick");
wait();
}
catch(InterruptedException e){}
}
available=false;
}

public synchronized void putdown(){

available=true;
notify();
}
}


class Hello extends Thread{

ChopStick left,right;

int hello_num;

Hello(int num,ChopStick chop1,ChopStick chop2){

hello_num=num;
left=chop1;
right=chop2;
}

public void eat(){

left.takeup();
right.takeup();
System.out.println("Hello "+(hello_num+1)+" is eating");
}

public void think(){

left.putdown();
right.putdown();

System.out.println("Hello "+(hello_num+1)+" is THinking");
}

public void run(){

while(true){

eat();
try
{
sleep(1000);
}
catch(InterruptedException ex){}

think();

try
{
sleep(1000);
}
catch(InterruptedException ex){}

}
}
}




class ThreadAllDemo{

static ChopStick[] chopsticks=new ChopStick[5];
static Hello[] hellos=new Hello[5];

public static void main(String a[]){

for(int count=0;count<=4;count++){

chopsticks[count]=new ChopStick();
}

for(int count=0;count<=4;count++){

hellos[count]=new Hello(count,chopsticks[count],chopsticks[(count+1)%5]);
}


for(int count=0;count<=4;count++){

hellos[count].start();
}
}
}

Thread Synchronization Methods

class One{

synchronized void display(int num){

System.out.println(""+num);

try
{

Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Error : "+e);
}
System.out.println("Done");
}
}

class Two implements Runnable{

int number;
One objo;
Thread objo1;

public Two(One one_num,int num){

objo=one_num;

number=num;

objo1=new Thread(this);
objo1.start();
}

public void run(){

objo.display(number);
}
}


class SynchMethod{
public static void main(String a[]){


One objo=new One();

int digit=10;

Two objSynch1=new Two(objo,digit++);
Two objSynch2=new Two(objo,digit++);
Two objSynch3=new Two(objo,digit++);

//wait for THreads to end

try
{

objSynch1.objo1.join();
objSynch2.objo1.join();
objSynch3.objo1.join();
}
catch(InterruptedException ex){
System.out.println("Error : "+ex);
}

}
}

Thread Synchronization

class DemoOne{

void display(int num){

System.out.println(""+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("Done");
}
}



class DemoTwo implements Runnable{

int number;
DemoOne objone;
Thread objTh;

public DemoTwo(DemoOne one_num,int num){

objone=one_num;
number=num;

objTh=new Thread(this);

objTh.start();
}

public void run(){

synchronized(objone){
objone.display(number);
}
}
}



class SynchBlock{

public static void main(String a[]){

DemoOne objone=new DemoOne();

int digit=10;

DemoTwo objSynch1=new DemoTwo(objone,digit++);
DemoTwo objSynch2=new DemoTwo(objone,digit++);
DemoTwo objSynch3=new DemoTwo(objone,digit++);

try
{//wait for Threads to end

objSynch1.objTh.join();
objSynch2.objTh.join();
objSynch3.objTh.join();
}
catch(InterruptedException ex){
System.out.println("Error : "+ex);
}
}
}