130 likes | 528 Views
DISTRIBUTED SYSTEMS Principles and Paradigms Second Edition ANDREW S. TANENBAUM MAARTEN VAN STEEN Chapter 3 Processes. Example: Java. - main thread - minor thread by main thread (share cpu time) - last terminated thread: main thread class mythread{ public static void main(String[]args){
E N D
DISTRIBUTED SYSTEMSPrinciples and ParadigmsSecond EditionANDREW S. TANENBAUMMAARTEN VAN STEENChapter 3Processes Tanenbaum & Van Steen, Distributed Systems: Principles and Paradigms, 2e, (c) 2007 Prentice-Hall, Inc. All rights reserved. 0-13-239227-5
Example: Java - main thread - minor thread by main thread (share cpu time) - last terminated thread: main thread class mythread{ public static void main(String[]args){ Thread t; t=Thread.currentThread(); System.out.println(t); Thread[main,5,main] t.setName(“thread1”); System.out.println(t);--> Thread[thread1,5,main]
Example: thread creation class Thread2 extends Thread{ public Thread2(){ System.out.println(“second thread starting”);} public void run(){ for(inti=0;i<500;i++) System.out.println(“turn second”+i);} } class mainthread{ Public static void main(Sting[]args){ Thread2 t=new Thread2(); t.start(); concurrency for(inti=0;i<500;i++) System.out.println(“turn main:”+i);} } T0RG T0RL T1RG T1RL
example class Newthread extends Thread{ public void run(){ try{ for(int i=0;i<500;i++){ System.out.println(“child is sleeping”); Thread.sleep(2000);} } catch(InterruptedException e){ System.out.println(“child interrupted”);} System.out.println(“exit child”); } …….> cont. next page
From previous pag class mainthread{ public static void main(String[]args){ System.out.println(“befor….”); Newthread t1=new Newthread(); t1.start(); System.out.println(“after….”); try{ For(int j=0;j<500;j++){ System.out.println(“main starting:”+j); Thread.sleep(2000); If(j==25) t1.Interrupt();} } catch(InterruptedException e){ System.out.println(“main interrupted”);} System.out.println(“exit main”); }
Threads • thread: virtual processors (VP) in software, on top of physical processors • VP: set of instructions • stopping the current VP and saving all the data needed to continue the execution at a later stage. • Process: actual software processor threads • lightweight process = thread