Experiment code:
package demo2; public class SaleTicker implements Runnable { public int total=1000; public int count=0; @Override public void run() { while(total>0){ synchronized(this){ if(total>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count++; total--; System.out.println(Thread.currentThread().getName()+"\t当前票号:"+count); } } } } }package demo2; public class SaleTicker implements Runnable { public int total=1000; public int count=0; @Override public void run() { while(total>0){ synchronized(this){ if(total>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count++; total--; System.out.println(Thread.currentThread().getName()+"\t当前票号:"+count); } } } } } package demo2; public class Test { public static void main(String[] args) { SaleTicker st=new SaleTicker(); for(int i=1;i<=10;i++){ new Thread(st,"售票点"+i).start();; } } }
Screenshot experiment code:
Screenshot results:
Week Nine Summary:
This week the main learning multithreaded java input and output;
Multi-threaded mainly two:
1. thread class inheritance;
2 runnable interfaces implemented;
start () method is to start multi-threaded;
run () is the main multi-threaded;
Two differences:
thread can not share resources;
runnable to achieve resource sharing;
java input and output:
Flile main usage and constants: