標籤:.com stat one nbsp bsp ttext -- round nts
範例程式碼:
多線程,並設定優先權:
1 package signal; 2 3 4 class A extends Thread{ 5 public void run(){ 6 for(int i=1;i<=3;i++){ 7 System.out.println("a" +i); 8 } 9 }10 }11 class B extends Thread{12 public void run(){13 for(int i=1;i<=3;i++){14 System.out.println("b" +i);15 }16 }17 }18 19 class C extends Thread{20 public void run(){21 for(int i=1;i<=3;i++){22 System.out.println("c" +i);23 }24 }25 }26 27 public class first {28 public static void main (String args[]){29 A a =new A();30 B b =new B();31 C c =new C();32 33 a.setPriority(Thread.MAX_PRIORITY);34 b.setPriority(Thread.NORM_PRIORITY);35 c.setPriority(Thread.MIN_PRIORITY);36 37 a.start();38 b.start ();39 c.start ();40 41 }42 43 }View Code
測試結果:
優先順序的設定並不是一定會遵循這個優先順序,只是按照優先順序的機率會大一些。
情景:
利用多線程,控制交通號誌
設定交通號誌:
1 package signal; 2 3 import java.awt.Color; 4 5 import javax.swing.JFrame; 6 import javax.swing.JLabel; 7 import javax.swing.JPanel; 8 9 public class signalDemo extends JFrame implements Runnable {10 JPanel red ,yellow ,green;11 JLabel time ,show;12 13 14 15 @Override16 public void run() {17 18 19 try{20 while(true){21 red.setBackground(Color.red);22 yellow.setBackground(Color.gray);23 green.setBackground(Color.gray);24 for(int i=3;i>0;i++){25 String s =Integer.toString(i);26 show.setText(s+"-stop-");27 Thread.sleep(1000);28 }29 yellow.setBackground(Color.gray);30 green.setBackground(Color.green);31 red.setBackground(Color.gray);32 for(int i=5;i>0;i--){33 String s =Integer.toString(i);34 show.setText(s+"-go-");35 Thread.sleep(1000);36 }37 38 yellow.setBackground(Color.yellow);39 green.setBackground(Color.gray);40 red.setBackground(Color.gray);41 for(int i=2;i>0;i--){42 String s =Integer.toString(i);43 show.setText(s+"-get slow-");44 Thread.sleep(1000);45 }46 }47 }48 catch(InterruptedException e){49 System.out.println(e);50 }51 }52 signalDemo(){53 this.getContentPane().setBackground(Color.black);54 this.setSize(100,260);55 this.setVisible(true);56 this.setLocationRelativeTo(null);57 58 59 red=new JPanel();60 red.setBackground(Color.red);61 62 green=new JPanel();63 green.setBackground(Color.green);64 65 yellow=new JPanel();66 yellow.setBackground(Color.yellow);67 68 setLayout(null);69 red.setBounds(40,20,40,40);70 add(red);71 72 green.setBounds(40,70,40,40);73 add(green);74 75 yellow.setBounds(40,120,40,40);76 add(yellow);77 78 time =new JLabel("Time remain ");79 time.setForeground(Color.white);80 time.setBounds(20,160,100,40);81 add(time);82 show =new JLabel("");83 show.setBounds(38,178,80,40);84 show.setForeground(Color.cyan);85 add(show);86 }87 88 public static void main(String args[]){89 signalDemo sn=new signalDemo();90 Thread task=new Thread(sn);91 task.start();92 93 }94 95 }View Code
測試結果:
Java--多執行緒