Java--多线程处理
Posted Catherine_zhilin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java--多线程处理相关的知识,希望对你有一定的参考价值。
示例代码:
多线程,并设置优先级:
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 }
测试结果:
优先级的设置并不是一定会遵循这个优先级,只是按照优先级的概率会大一些。
情景:
利用多线程,控制交通信号灯
设置交通信号灯:
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 @Override 16 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 }
测试结果:
以上是关于Java--多线程处理的主要内容,如果未能解决你的问题,请参考以下文章