SlideShare uma empresa 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();     } } 

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante 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
 

Semelhante 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

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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();     } }