一,区分进程与线程 1,进程 每一个应用程序就是一个进程 2,线程 每个进程包含多个线程用来实现不同任务 二,建立线程的方式(两种) 1,通过继承Thread类 创建一个thread的子类 xxxthread 通过直接 new xxxthread() 的方式 创建线程对象 如:public class MyThread extends Thread{ @Override public void run(){ super.run(); try{ Thread.sleep(2000); }catch (InterruptedException e){ e.printStackTrace(); }finally{ }System.out.println(“我是一个线程”); } }
main中: public static void main(String[] args) throws InterruptedException{
MyThread myThread = new MyThread(); myThread.start(); } 2,通过实现Runable 接口的方式 如: public class MyRunable implements Runable{ @Override public void run(){ super.run(); try{ Thread.sleep(2000); }catch (InterruptedException e){ e.printStackTrace(); }finally{ }System.out.println(“我是正在执行的myrunable:” + i); } }
main: MyRunnable myRunnable = new MyRunnable; Thread t = new Thread(myRunnable); t.start; 三,另一种方式 1,private static void show3() { new Thread(new Runnable() { @Override public void run() { while (true){ System.out.println(“我是第一个线程”); } } }).start(); 2,new Thread(){ @Override public void run() { super.run(); while (true){ System.out.println(“—–”); } } }.start(); } 线程的运行方式为抢占式运行
四,public class Another extends Thread{ @override public void run(){ super.run(); for(int i =0;i <1000;i ++){ } System.out.println(“我是另一个线程:” +getState()); } } public class LifeThread extends Thread{ private Another another; public LifeThread(Another another){ this.another=another; } @Override public void run(){ super.run(); for(int i = 0;i<1000;i++){ System.out.println(“life—”+getState()+”—”+another.getState() );} } } private static void show(){ Another a = new Another(); LifeThread l = new LifeThread(a); a.star(); l.star(); System.out.println(“主线程跑完了”); } 五 死锁 public class PrinterDeadLock { private String s1 =”我是s1”; private String s2 =”我是s2”; public void p1() { synchronized (s1) { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(“s1锁住了p1”);
synchronized (s2) { for (int i = 0; i < 20; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("s2锁住了p1"); } } } } public void p2() { synchronized (s2) { System.out.println("s2锁住了p2"); synchronized (s1) { for (int i = 0; i < 20; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("s1锁住了p2"); } } } }} 六 锁 synchronized public class SynDemo{ private static Integer count=10000; public synchronized void del (){ for(int i= 0; i<2500;i++){ count-=1; System.out.println(Thread.currentThread.getName()+”—–”+count); }} } /锁是什么 //锁是一个对像 //假如A线程先访问这个del方法, //那么锁对象就会被A线程持有 //那么其他线程想访问这个del方法的时候就会发现锁对象被A拿走了 //不能进入到del方法中 //当A执行完毕del方法的时候 会将锁释放出来 //这时候B C D 再争夺执行权 //谁抢到了 谁来执行 //再和A一样