多线程(1)
java 编程思想-- 继承自Thread :
package com.xtl.java; public class test extends Thread{ private int countDown = 6; private int threadCount = 0; private int threadNumber = ++threadCount; public test(int a ){ threadNumber = a; System.out.println("Making " + threadNumber ); } public void run(){ while(true){ System.out.println("Thread " + threadNumber+"("+countDown+")"); if(--countDown==0){ return ;} } } public static void main(String[] args){ for(int i = 0;i<5; i++){ new test(i).start(); } System.out.println("All Threads Started"); } }
首先SimpleThread 继承了Thread 这个类,Thread 中最主要的是run (); 你必须覆写它,使线程执行你所指派的工作。因此run () 是程序中会和其他线程“同时”执行的部分。
run() 实际上具有某种形式的循环,此种循环会不断的执行,直到程序不再需要该线程为止。所以你必须设定此循环的脱离条件(或是和上例一样直接从run() 回返)。
package com.xtl.java; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JApplet; public class test extends JApplet{ private class SeparateSubTask extends Thread{ private int count = 0; private boolean runFlag = true; SeparateSubTask(){ start(); } void invertFlag() { runFlag = !runFlag; } public void run (){ while(true){ try{ sleep(1000); }catch(InterruptedException e) { System.err.println("Interrupted"); } if(runFlag) { t.setText(Integer.toString(count++)); } } } } private SeparateSubTask sp = null; private JTextField t = new JTextField(10); private JButton start = new JButton("Start"),onOff = new JButton("Toggle"); class StartL implements ActionListener { public void actionPerformed(ActionEvent e){ if(sp == null){ sp = new SeparateSubTask(); } } } class OnOffL implements ActionListener{ public void actionPerformed(ActionEvent e){ if(sp !=null){ sp.invertFlag(); } } } public void init (){ Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t); start.addActionListener(new StartL()); cp.add(start); onOff.addActionListener(new OnOffL()); cp.add(onOff); } public static void main(String[] args){ test t = new test(); JFrame frame = new JFrame("test"); frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e ){ System.exit(0); } }); frame.getContentPane().add(t); frame.setSize(300,100); t.init(); t.start(); frame.setVisible(true); } }