什么是线程
线程是进程的执行单元,比如进程就是一个工厂,线程就是工厂内的各个车间。
线程的基本操作
1新建线程,2种方法,一种是实现runable接口,一种是继承Thread类
public class Main {
public static void main1(String[] args) {
//新建线程
Thread tt =new Thread() {
public void run() {
System.out.println("Hello World!");
}
};
tt.start();
tt.run();//这个不能开启线程这个只是运行Thread里的run方法
}
2终止线程
Thread.stop()不推荐使用,它会释放所有的monitor,比如有2条数据
ID name age
1 张三 22
2 李四 24
3中断线程
public void Thread.interrupt();//中断线程 public boolean Thread.isInterrupt();//判断是否被中断 public static boolean Thread.interrupted();//判断是否被中断,并清除当前中断状态
4挂起(suspend)和继续执行(resume)线程public static void main(String[] args) throws Exception{ Thread tt =new Thread() { public void run() { while(true){ if(Thread.currentThread().isInterrupted()){ System.out.println("Interrupted"); break; } Thread.yield(); } } }; tt.start(); tt.sleep(2000); tt.interrupt(); }
-suspend()不会释放锁
-如果加锁发生在resume()之前,则死锁发生
5等待线程结束(join)和谦让(yeild)
/** * Created by Administrator on 2016/11/9. */ public class JoinTest { public volatile static int i=0; public static class AddThread extends Thread{ public void run(){ for(i=0;i<100;i++){ System.out.print("开始报数"+i+"/s/n"); } } } public static void main(String args[])throws InterruptedException{ AddThread ad =new AddThread(); ad.start(); // ad.join();//join的作用就是等上面执行完毕,然后接着执行下面的东东 System.out.println("报告完毕!!!!!!"+i); } }
守护线程
-在后头默默地完成一些系统性的服务,比如垃圾回收线程,JIT线程就可以理解为守护线程
-当一个Java应用内,只有守护线程时,Java虚拟机就会自然退出
Thread t =new Thread();
t.setDaemon(true);
t.start();
线程的优先级
public final static int MIN_PRIORITY=1;
public final static int NORM_PRIORITY=5;
public final static int MAX_PRIORITY=10;
<pre name="code" class="java"> Thread high =new Thread();
Thread low =new Thread();
high.setPriority(MAX_PRIORITY);
low.setPriority(MIN_PRIORITY);
high.start();
low.start();
优先级高的线程更容易在竞争中获胜
基本的线程同步操作
synchronized
– 指定加锁对象:对给定对象加锁,进入同步代码前要获得给定对象的锁。
– 直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
– 直接作用于静态方法:相当于对当前类加锁,进入同步代码前要获得当前类的锁。
Object.wait() Obejct.notify()
/**
* Created by Administrator on 2016/11/9.
*/
public class Test2 {
private static Object object="Test";
public static class t1 extends Thread{
public void run(){
synchronized (object){
System.out.println(System.currentTimeMillis()+":t1 start!");
try{
System.out.println(System.currentTimeMillis()+":t1 wait for object!");
object.wait();
}catch(InterruptedException e){
}
System.out.println(System.currentTimeMillis()+":t1 end!");
}
}
}
public static class t2 extends Thread{
public void run(){
synchronized (object){
System.out.println(System.currentTimeMillis()+":t2 start! notify one thread");
object.notify();
System.out.println(System.currentTimeMillis()+":t2 end!");
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
public static void main(String args[]){
Thread t11=new Thread(new t1());
Thread t22=new Thread(new t2());
t11.start();
t22.start();
}
}