进程(Process)是计算机中的程序关于某数据集合上的一次运行活动
线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元,在单个程序中同时运行多个线程完成不同的工作,称为多线程。
public class GUI {
public static void main(String[] args) {
System.out.println("xiaolan");
char arr[]={'I',' ','L','O','V','E',' ','Y','O','U'};
try{
for(int i=0;i<arr.length;i++)
{
Thread.sleep(500);//1000=1秒
System.out.print(arr[i]);
}
System.out.println("");
Thread.sleep(1200);
System.out.println("Would you wanne be my girlfriend ?");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
创建自己的多线程函数
- 方法一 继承一个线程
class myclass extends Thread
{
public staric void main(String[] args)
{
myclass obj = new myclass();
obj.start();
}
}
- 方法二: Runnable(可运行) 接口(interface)//多数用这种
class myclass extends JFrame implements Runnable
{
public void run()
{
//.....
}
public staric void main(String[] args)
{
myclass obj = new myclass();
Thread th = new Thread(obj);
th.start();
}
}
线程的生命周期
- 新生(New)
- 可运行(Runnable)
- 不可运行 (Not Runnable) :sleep休眠、wait等待、被其他线程阻止
- 终止或死亡(Terminated or Dead):代码执行完(自然死亡),强制死亡
线程优先级
Java线程可以有优先级的设定,高优先级的线程比低优先级的线程** 有更高的几率 **得到执行
优先级范围: 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY ),默认优先级5(NORM_PRIORITY)
对象.setPriority()
控制线程生命周期
对象.isAlive() //自己判断自己是不是活着?
对象.stop()//强制把线程给停,线程的开启和死亡都需要时间,强烈不要用这种方法去停,会发生线程安全问题
正确暂停方法:
if(Thread.currentThread().isInterrupted())
{
return;
}
t.interrupt();//标记一个线程处于停止状态,不是立刻死亡
t.sleep(1000);//睡眠1秒钟-线程停止需要一定时间
用线程生命期写一个倒计时程序
package gui;
import java.awt.*;
import javax.swing.*;
public class GUI extends Thread{
JTextField tf;
JLabel l;
JFrame fr;
public void run()
{
buildGUI();
}
void display()
{
for(int i =30; i>=0;i--)
{
try
{
Thread.sleep(1000);
String s =Integer.toString(i);
tf.setText(" " + s + " seconds to go..");
}
catch(Exception e){
System.out.println(e);
}
}
JOptionPane.showMessageDialog(fr, "Time out !!!");
tf.setText("");
tf.setEditable(false);
}
public void buildGUI(){
fr = new JFrame("Countown Timer");
JPanel p = new JPanel();
l = new JLabel(" ");
tf = new JTextField(15);
tf.setEnabled(false);
Font f = new Font("Verdana",0,18);
tf.setFont(f);
tf.setBackground(Color.blue);
fr.add(p);
p.add(tf);
p.add(l);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(300,100);
fr.setResizable(false);
display();
}
public static void main(String[] args) {
GUI obj = new GUI();
obj.start();
}
}
并发:任务分开运行,快速切换
并行:多个任务同时进行