Thread in Adv Java
Thread in Adv Java
Result:
value of i is 1
value of i is 2
value of i is 3
value of i is 4
value of i is 5
value of i is 6
value of i is 7
value of i is 8
value of i is 9
value of i is 10
//creating our thread using Runnable interface
class MyThread implements Runnable
{
public void run(){
// task for thread...
for(int i=1;i<=10;i++)
{
System.out.println("value of i is "+i);
try {
Thread.sleep(5000);
}catch(Exception e){
}
}
}
public static void main(String[] args){
//create object of Mythread class
MyThread t1=new MyThread();
Thread thr=new Thread(t1);
thr.start();
}
}
• //setName
• t.setName("MyMain");
• System.out.println(t.getName());
• try{
• Thread.sleep(5000);
• }catch(Exception e){
• };
• System.out.println(t.getId());
• System.out.println("program ended...");
• }
• }
1st company
• class Company
• {
• int n;
• synchronized public void produce_item(int n)
• {
• this.n=n;
• System.out.println("Produced : "+this.n);
• }
•
synchronized public int consume_item()
• {
• System.out.println("Consumed : "+this.n);
• return this.n;
• }
•
}
2 Producer
nd
• class Main
• {
• public static void main(String[] args) {
• Company comp=new Company();
• Producer p=new Producer(comp);
• Consumer c=new Consumer(comp);
• p.start();
• c.start();
• }
• }
Run in cmd
• Javac Company.java
• Javac Producer.java
• Javac Consumer.java
• Javac Main.java
• Java Main