SlideShare una empresa de Scribd logo
1 de 19
14 Thread HUREE University ICT Instructor: M.J LEE
Thread 1 Process == 1 Program 1 Process == some Thread, like methods Thread is method in a program Threads can be executed simultaneously. How can we execute threads at the same time? simultaneously? 2
3 Thread Creation class Top implements Runnable{      public void run(){          for(inti=0; i<50; i++)  System.out.print(i+"");  }  }  public class ThreadMain{      public static void main(String[] args){  System.out.println("getting start!");          Top t = new Top();  Thread thd = new Thread(t);  thd.start();  System.out.println("the end");  }  } 1 2 3 4 5
Thread Creation 2 class Top implements Runnable{      public void run(){          for(inti=0; i<50; i++)  System.out.print(i+"");  }  }  public class ThreadMain2{      public static void main(String[] args){  System.out.println("getting start!");          Top t = new Top();  Thread thd1 = new Thread(t);  	  Thread thd2 = new Thread(t);         thd1.start();          thd2.start(); System.out.println("the end");  }  } 1 2 3 4 5 6 4
class RunFrame extends Frame implements Runnable {      public void run() {  inti = 0;  System.out.println("getting start!");          while(i<20) {  System.out.print(i + "");  this.setTitle("operating...." + i++);              try{  Thread.sleep(300);              } catch(InterruptedException e) {  System.out.println(e);}  }  System.out.println("the end!");  }  } public class RunFrameMain{  	public static void main(String args[]){  RunFrame r = new RunFrame();  r.setSize(300, 100);  r.setVisible(true); Thread t = new Thread(r);  t.start();  	}  } 1 5
class RunnableFrame extends Frame implements Runnable {      public RunnableFrame() {          new Thread(this).start();  }      public void run() {  inti = 0;  System.out.println("getting start!");          while(i<20) {  System.out.print(i + "");  this.setTitle("operating" + i++);              try{  Thread.sleep(300);              }catch(InterruptedException e) {  System.out.println(e);}  }  System.out.println("the end!");  }  }  public class RunnableFrameMain{     public static void main(String args[]){  RunnableFrame r = new RunnableFrame();  r.setSize(300, 100);  r.setVisible(true); }   }  1 6
Control Threads 7 Sleep(time) For indicated time, the thread would be in “NotRunable” state. It would get back in “Runable” state. According to the priorities of threads, one thread would be in “run” state. When the thread be called, its statewould be exchanged automatically. Compulsory, Wait(): move the thread into “NotRunnable” state. Notify(): get back to the “Runable” state When the thread has done his work, it would be in “dead” state
Priority High priority == how often it would be in “Run” state. System Constants Set the priority  Get the priority of the thread in operation 8 public static final int MIN_PRIORITY = 1; public static final int NORM_PRIORITY = 5; public static final int MAX_PRIORITY = 10;  PriorityThread t = new PriorityThread(); t.setPriority(1); //t.setPriority(Thread.MIN_PRIORITY); t.setPriority(5); //t.setPriority(Thread.NORM_PRIORITY);  t.setPriority(10);//t.setPriority(Thread.MAX_PRIORITY);   int p = t.getPriority();
Priority Example 9 class PriorityThreadextends Thread {                              public void run() {  inti = 0;  System.out.print(this.getName());  System.out.println("[priority:“                + this.getPriority() + "] start");          while(i < 10000) {  i = i + 1;              try{  this.sleep(2);              }catch(Exception e){System.out.println(e);}  }  System.out.print(this.getName());  System.out.println("[priority:"                 + this.getPriority() + "] end");  }  }
10 public class PriorityThreadMain {  public static void main(String[] args) {  System.out.println("Main starts");  for(int i=1; i<=10; i++){  //for(inti=Thread.MIN_PRIORITY;i<=Thread.MAX_PRIORITY; i++) 	  {  PriorityThread s = new PriorityThread();  s.setPriority(i);  s.start();  }  System.out.println("Main ends");     }//end of main  } 1 2
NotRunnable state 11 Automatically… Be in wait mode for a while Sleep() Intentionally… Control between NotRunnable state and Runnable state Waite(), notify()
12 import java.util.*;  class NotRunnableThread extends Thread {  public void run() {  inti = 0;  while(i < 10) {  System.out.println(i + "th :"  			+ System.currentTimeMillis() + "");  i = i + 1;  try{  this.sleep(1000);              }catch(Exception e){System.out.println(e);}  }  }  } public class NotRunnableMain {  	public static void main(String args[] ) {  NotRunnableThread s = new NotRunnableThread();  s.start();  	} } 2 1
Thread Termination 13 Generally, run() termination means thread termination
14 class TerminateThread extends Thread {  private boolean flag = false;      public void run() {  int count = 0;  System.out.println(this.getName() +"start");  while(!flag) {  try { this.sleep(100);              } catch(InterruptedException e) {  }  }  System.out.println(this.getName() +"end");  }      public void setFlag(boolean flag){  this.flag = flag;  }  } public class TerminateMain {      public static void main(String args[])throws Exception{  System.out.println("start");  TerminateThread a = new TerminateThread();  TerminateThread b = new TerminateThread();  TerminateThread c = new TerminateThread(); Flag setting for controlling threads 1 2 Flag setting for controlling threads
15 a.start();  b.start();  c.start();  inti;  System.out.print(“type thread A, B, C, M?");  while(true){  i = System.in.read();  if(i == 'A'){  a.setFlag(true);              }else if(i == 'B'){  b.setFlag(true);              }else if(i == 'C'){  c.setFlag(true);              }else if(i == 'M'){  a.setFlag(true);  b.setFlag(true);  c.setFlag(true);  System.out.println("main ends");  break;  }  }  }   } All threads has been moved in Runnable state. They are ready to run. 3 Read one character like scanf() in C language 4 5 If flag is true...
Shared Resource : Synchronization 16 Synchronization The method to share resource To use shared resource in the order Implementation Lock on the resources Wait() notify() public synchronized void saveMoney(int save){  	//....shared resource } public void saveMoney(int save){  	synchronized(this) { 		//....shared resource  	} }
17 class Bank{     private int money = 10000; //balance    public int getMoney(){ return this.money; }     public void setMoney(int money){         this.money = money;     }     public synchronized void saveMoney(int save){         int m = this.getMoney();         try{             Thread.sleep(3000);         }catch(InterruptedException e){e.printStackTrace();}         this.setMoney(m + save);     }     public void minusMoney(int minus){         synchronized(this){             int m = this.money;             try{                 Thread.sleep(200);             }catch(InterruptedException e){e.printStackTrace();}             this.setMoney(m - minus);         }    } }  1 2 3.1 3.2 Where is the shared resource? In THIS class!!
18 class You extends Thread{     public void run(){         SyncMain.myBank.saveMoney(3000);          System.out.println("saveMoney(3000):"  			+ SyncMain.myBank.getMoney());     } } class YourWife extends Thread{     public void run(){         SyncMain.myBank.minusMoney(1000);          System.out.println("minusMoney(3000):"  			+ SyncMain.myBank.getMoney());     } }  Flag setting for controlling threads 1 2 Flag setting for controlling threads
19 public class SyncMain{     public static Bank myBank = new Bank();     public static void main(String[] args) throws Exception{         You y = new You();         YourWife w = new YourWife();         y.start();         try{             Thread.sleep(200);         }catch(InterruptedException e){e.printStackTrace();}         yw.start();     } } 

Más contenido relacionado

La actualidad más candente

The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180Mahmoud Samir Fayed
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 87 of 202
The Ring programming language version 1.8 book - Part 87 of 202The Ring programming language version 1.8 book - Part 87 of 202
The Ring programming language version 1.8 book - Part 87 of 202Mahmoud Samir Fayed
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88Mahmoud Samir Fayed
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212Mahmoud Samir Fayed
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoChih-Hsuan Kuo
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84Mahmoud Samir Fayed
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019Gebreigziabher Ab
 
Exception handling
Exception handlingException handling
Exception handlingKapish Joshi
 

La actualidad más candente (19)

Java practical
Java practicalJava practical
Java practical
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181
 
Java file
Java fileJava file
Java file
 
The Ring programming language version 1.8 book - Part 87 of 202
The Ring programming language version 1.8 book - Part 87 of 202The Ring programming language version 1.8 book - Part 87 of 202
The Ring programming language version 1.8 book - Part 87 of 202
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Class 5 2ciclo
Class 5 2cicloClass 5 2ciclo
Class 5 2ciclo
 
Play image
Play imagePlay image
Play image
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019
 
Exception handling
Exception handlingException handling
Exception handling
 

Similar a 14 thread

Java interface and inheritance
Java interface and inheritanceJava interface and inheritance
Java interface and inheritanceJaromirJagr
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 
Methods Of Thread Class
Methods Of Thread ClassMethods Of Thread Class
Methods Of Thread Classkqibtiya5
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfpublic static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfarihanthtoysandgifts
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 

Similar a 14 thread (20)

Java interface and inheritance
Java interface and inheritanceJava interface and inheritance
Java interface and inheritance
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Java file
Java fileJava file
Java file
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Methods Of Thread Class
Methods Of Thread ClassMethods Of Thread Class
Methods Of Thread Class
 
STS4022 Exceptional_Handling
STS4022  Exceptional_HandlingSTS4022  Exceptional_Handling
STS4022 Exceptional_Handling
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
作業系統
作業系統作業系統
作業系統
 
Generics
GenericsGenerics
Generics
 
My java file
My java fileMy java file
My java file
 
Java programs
Java programsJava programs
Java programs
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Thread
ThreadThread
Thread
 
Threads
ThreadsThreads
Threads
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfpublic static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 

Último

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Último (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

14 thread

  • 1. 14 Thread HUREE University ICT Instructor: M.J LEE
  • 2. Thread 1 Process == 1 Program 1 Process == some Thread, like methods Thread is method in a program Threads can be executed simultaneously. How can we execute threads at the same time? simultaneously? 2
  • 3. 3 Thread Creation class Top implements Runnable{ public void run(){ for(inti=0; i<50; i++) System.out.print(i+""); } } public class ThreadMain{ public static void main(String[] args){ System.out.println("getting start!"); Top t = new Top(); Thread thd = new Thread(t); thd.start(); System.out.println("the end"); } } 1 2 3 4 5
  • 4. Thread Creation 2 class Top implements Runnable{ public void run(){ for(inti=0; i<50; i++) System.out.print(i+""); } } public class ThreadMain2{ public static void main(String[] args){ System.out.println("getting start!"); Top t = new Top(); Thread thd1 = new Thread(t); Thread thd2 = new Thread(t); thd1.start(); thd2.start(); System.out.println("the end"); } } 1 2 3 4 5 6 4
  • 5. class RunFrame extends Frame implements Runnable { public void run() { inti = 0; System.out.println("getting start!"); while(i<20) { System.out.print(i + ""); this.setTitle("operating...." + i++); try{ Thread.sleep(300); } catch(InterruptedException e) { System.out.println(e);} } System.out.println("the end!"); } } public class RunFrameMain{ public static void main(String args[]){ RunFrame r = new RunFrame(); r.setSize(300, 100); r.setVisible(true); Thread t = new Thread(r); t.start(); } } 1 5
  • 6. class RunnableFrame extends Frame implements Runnable { public RunnableFrame() { new Thread(this).start(); } public void run() { inti = 0; System.out.println("getting start!"); while(i<20) { System.out.print(i + ""); this.setTitle("operating" + i++); try{ Thread.sleep(300); }catch(InterruptedException e) { System.out.println(e);} } System.out.println("the end!"); } } public class RunnableFrameMain{ public static void main(String args[]){ RunnableFrame r = new RunnableFrame(); r.setSize(300, 100); r.setVisible(true); } } 1 6
  • 7. Control Threads 7 Sleep(time) For indicated time, the thread would be in “NotRunable” state. It would get back in “Runable” state. According to the priorities of threads, one thread would be in “run” state. When the thread be called, its statewould be exchanged automatically. Compulsory, Wait(): move the thread into “NotRunnable” state. Notify(): get back to the “Runable” state When the thread has done his work, it would be in “dead” state
  • 8. Priority High priority == how often it would be in “Run” state. System Constants Set the priority Get the priority of the thread in operation 8 public static final int MIN_PRIORITY = 1; public static final int NORM_PRIORITY = 5; public static final int MAX_PRIORITY = 10; PriorityThread t = new PriorityThread(); t.setPriority(1); //t.setPriority(Thread.MIN_PRIORITY); t.setPriority(5); //t.setPriority(Thread.NORM_PRIORITY); t.setPriority(10);//t.setPriority(Thread.MAX_PRIORITY);  int p = t.getPriority();
  • 9. Priority Example 9 class PriorityThreadextends Thread { public void run() { inti = 0; System.out.print(this.getName()); System.out.println("[priority:“ + this.getPriority() + "] start"); while(i < 10000) { i = i + 1; try{ this.sleep(2); }catch(Exception e){System.out.println(e);} } System.out.print(this.getName()); System.out.println("[priority:" + this.getPriority() + "] end"); } }
  • 10. 10 public class PriorityThreadMain { public static void main(String[] args) { System.out.println("Main starts"); for(int i=1; i<=10; i++){ //for(inti=Thread.MIN_PRIORITY;i<=Thread.MAX_PRIORITY; i++) { PriorityThread s = new PriorityThread(); s.setPriority(i); s.start(); } System.out.println("Main ends"); }//end of main } 1 2
  • 11. NotRunnable state 11 Automatically… Be in wait mode for a while Sleep() Intentionally… Control between NotRunnable state and Runnable state Waite(), notify()
  • 12. 12 import java.util.*; class NotRunnableThread extends Thread { public void run() { inti = 0; while(i < 10) { System.out.println(i + "th :" + System.currentTimeMillis() + ""); i = i + 1; try{ this.sleep(1000); }catch(Exception e){System.out.println(e);} } } } public class NotRunnableMain { public static void main(String args[] ) { NotRunnableThread s = new NotRunnableThread(); s.start(); } } 2 1
  • 13. Thread Termination 13 Generally, run() termination means thread termination
  • 14. 14 class TerminateThread extends Thread { private boolean flag = false; public void run() { int count = 0; System.out.println(this.getName() +"start"); while(!flag) { try { this.sleep(100); } catch(InterruptedException e) { } } System.out.println(this.getName() +"end"); } public void setFlag(boolean flag){ this.flag = flag; } } public class TerminateMain { public static void main(String args[])throws Exception{ System.out.println("start"); TerminateThread a = new TerminateThread(); TerminateThread b = new TerminateThread(); TerminateThread c = new TerminateThread(); Flag setting for controlling threads 1 2 Flag setting for controlling threads
  • 15. 15 a.start(); b.start(); c.start(); inti; System.out.print(“type thread A, B, C, M?"); while(true){ i = System.in.read(); if(i == 'A'){ a.setFlag(true); }else if(i == 'B'){ b.setFlag(true); }else if(i == 'C'){ c.setFlag(true); }else if(i == 'M'){ a.setFlag(true); b.setFlag(true); c.setFlag(true); System.out.println("main ends"); break; } } } } All threads has been moved in Runnable state. They are ready to run. 3 Read one character like scanf() in C language 4 5 If flag is true...
  • 16. Shared Resource : Synchronization 16 Synchronization The method to share resource To use shared resource in the order Implementation Lock on the resources Wait() notify() public synchronized void saveMoney(int save){ //....shared resource } public void saveMoney(int save){ synchronized(this) { //....shared resource } }
  • 17. 17 class Bank{     private int money = 10000; //balance    public int getMoney(){ return this.money; }     public void setMoney(int money){         this.money = money;     }     public synchronized void saveMoney(int save){         int m = this.getMoney();         try{             Thread.sleep(3000);         }catch(InterruptedException e){e.printStackTrace();}         this.setMoney(m + save);     }     public void minusMoney(int minus){         synchronized(this){             int m = this.money;             try{                 Thread.sleep(200);             }catch(InterruptedException e){e.printStackTrace();}             this.setMoney(m - minus);         }    } }  1 2 3.1 3.2 Where is the shared resource? In THIS class!!
  • 18. 18 class You extends Thread{     public void run(){         SyncMain.myBank.saveMoney(3000);          System.out.println("saveMoney(3000):"  + SyncMain.myBank.getMoney());     } } class YourWife extends Thread{     public void run(){         SyncMain.myBank.minusMoney(1000);          System.out.println("minusMoney(3000):"  + SyncMain.myBank.getMoney());     } }  Flag setting for controlling threads 1 2 Flag setting for controlling threads
  • 19. 19 public class SyncMain{     public static Bank myBank = new Bank();     public static void main(String[] args) throws Exception{         You y = new You();         YourWife w = new YourWife();         y.start();         try{             Thread.sleep(200);         }catch(InterruptedException e){e.printStackTrace();}         yw.start();     } }