Java线程初步

来源:互联网 发布:java 开源知识库 编辑:程序博客网 时间:2024/05/20 06:22
  • 线程基本概念

线程是一个程序内部的顺序控制流,也可以将线程看做是一个程序中不同的执行路径。

  • 线程和进程的基本区别

进程可以看做是静态的,在一个程序执行之前,在内存中会生成这个进程的代码空间和数据空间,并且一个进程的代码空间和数据空间一般情况下是独占的,不和其他进程共享(如果不进行交互的话);当这个程序开始执行,在这个进程中会产生一个主线程,然后这个主线程开始执行,如果有需要,这个主线程还会产生多个子线程并行执行,在宏观上看,这个进程开始执行了(实际上进程内部运行的是线程)。

  1. 进程有独立的代码和数据空间,而同一类线程共享代码段和数据空间,但是线程也有自己独立的运行栈和程序计数器(如果没有的话,线程并行运行起来就会出问题)。因此,进程间的相互切换的代价大于线程间的相互切换。
  2. 多线程和多进程:多线程是同一个程序中(同一类线程)多个不同的顺序流同时执行;多进程是操作系统中同时执行多个任务(程序)。

 

  • 如何产生一个并行执行的线程

一,继承Thread

package hq.org;public class TestThread1 extends Thread{private boolean flag = true;public static void main( String args[]){TestThread1 t = new TestThread1();t.start();for( int i=0; i<100; i++){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("I'm MainThread.");}t.endSubThread();System.out.println("MainThread Stoped.");}public void run(){while( this.flag ){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("----I'm SubThread.");}System.out.println("----SubThread Stoped.");}public void endSubThread(){this.flag = false;}}

二,实现runnable接口

package hq.org;public class TestThread {public static void main(String args[]){Runner1 r = new Runner1();Thread t1 = new Thread( r );t1.start();               //开始子线程             for( int i=0; i<50; i++) //主线程{try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(i + "I'm MainThread.");}r.endThread(); //停止子线程}}class Runner1 implements Runnable{private boolean flag = true;  //标识线程是否运行@Overridepublic void run() {   //重写run方法while( flag ){try {Thread.sleep(500);  } catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("-------I'm SubThread.");}}public void endThread() { //使得线程停止this.flag = false;}}

注意,这里对于产生一个新的进程,调用的都是start方法,要是直接调用run方法的话,那仅仅相当于调用某个方法,而不会产生一个新的进程去执行run方法。

除此之外,实现Runnable接口的方式比直接继承Thread类的方式要灵活。

 

  • sleepjoinyield方法

sleep方法:使线程暂停n个毫秒

join方法:线程1掉用线程2join方法,线程1将暂停等待线程2执行完,然后再接着往下执行

yeild方法:让步方法,暂时让出一下占用到的时间片,供其他线程使用

测试Join方法:

package hq.org;public class TestJoin {public static void main(String[] args) {MyThread2 t1 = new MyThread2("Thread 2");t1.start();for( int i=0; i<3; i++){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("i am main thread run with Thread2.");}try {t1.join();} catch (InterruptedException e) {}for (int i = 1; i <= 10; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("i am main thread run alone.");}}}class MyThread2 extends Thread {MyThread2(String s) {super(s);}public void run() {for (int i = 1; i <= 10; i++) {System.out.println("i am " + getName());try {sleep(1000);} catch (InterruptedException e) {return;}}}}

测试yeild方法:

package hq.org;public class TestYield {public static void main(String[] args) {MyThread3 t1 = new MyThread3("t1");MyThread3 t2 = new MyThread3("t2");t1.setPriority(1);t2.setPriority(5);t1.start();t2.start();}}class MyThread3 extends Thread {MyThread3(String s) {super(s);}public void run() {for (int i = 1; i <= 100; i++) {System.out.println(getName() + ": " + i);if (i % 10 == 0) {yield();}}}}

  • 线程同步
package hq.org;public class TestSync implements Runnable {Timer timer = new Timer();public static void main(String[] args) {TestSync test = new TestSync();Thread t1 = new Thread(test);Thread t2 = new Thread(test);t1.setName("t1");t2.setName("t2");t1.start();t2.start();}public void run() {timer.add(Thread.currentThread().getName());}}class Timer {private static int num = 0;public void add(String name) {num++;try {Thread.sleep(1);} catch (InterruptedException e) {}System.out.println(name + ", 你是第" + num + "个使用timer的线程");}}

不加synchronized关键字:


加synchronized关键字:


可能是打印不叫耗时,在一个线程对Timer对象里的num值自增1次后,还没来得及打印,另外一个线程又一次调用add方法,将num值再次增1,所以两次打印出来得结果都是2,如果要让这个程序合理的运行,可以对Timer类的add方法加上synchonized关键字修饰。

 

  • 一个简单的死锁
package hq.org;public class TestDeadLock implements Runnable {public int flag = 1;//两个临界资源static Object o1 = new Object(), o2 = new Object();public void run() {System.out.println("线程" + flag + "启动。。。");if (flag == 1) {//线程1,锁住资源1synchronized (o1) {System.out.println("线程1,锁住资源1");try {Thread.sleep(500);} catch (Exception e) {e.printStackTrace();}//线程1,锁住资源2synchronized (o2) {System.out.println("线程1,锁住资源2");}System.out.println("线程1结束。");}System.out.println("");}if (flag == 0) {//线程2,锁住资源2synchronized (o2) {System.out.println("线程2,锁住资源2");try {Thread.sleep(500);} catch (Exception e) {e.printStackTrace();}//线程2,锁住资源1synchronized (o1) {System.out.println("线程2,锁住资源1");}System.out.println("线程2结束。");}}}public static void main(String[] args) {TestDeadLock td1 = new TestDeadLock();TestDeadLock td2 = new TestDeadLock();td1.flag = 1;td2.flag = 0;Thread t1 = new Thread(td1);Thread t2 = new Thread(td2);t1.start();t2.start();}}


死锁结构图:




  • 一个简单的生产者和消费者程序
package hq.org;public class MyProducerConsumer {public static void main( String args[]){SynicStack synicStack = new SynicStack();Consummer cc = new Consummer(synicStack);Producer pp = new Producer(synicStack);Thread tc1 = new Thread( cc );Thread tc2 = new Thread( cc ); Thread tp = new Thread( pp );tp.start();tc1.start();tc2.start();}}class SynicStack {private final int stackLen = 10;private int[] res = new int[stackLen];private int top = -1;public synchronized void push(int res) {while (stackLen-1 == top) {// 如果栈满,等待try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}top++;this.res[top] = res;// 唤醒其他进程this.notifyAll();System.out.println("------Stack Length: " + top);}public synchronized int pop() {int ret = 0;while (-1 == top) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}ret = this.res[top];top--;// 唤醒其他进程this.notifyAll();System.out.println("------Stack Length: " + top);return ret;}}class Consummer implements Runnable {private final int numOfconsume = 20;private SynicStack synicStack = null;public Consummer(SynicStack ss) {this.synicStack = ss;}@Overridepublic void run() {for (int i = 0; i < numOfconsume; i++) {int getRes = this.synicStack.pop();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("consume Res: " + getRes);}}}class Producer implements Runnable {private final int numOfproduce = 40;private SynicStack synicStack = null;public Producer(SynicStack ss) {this.synicStack = ss;}public void run() {for (int i = 0; i < numOfproduce; i++) {synicStack.push(i);try{Thread.sleep(50);} catch (InterruptedException e){e.printStackTrace();}System.out.println(i + " was produced.");}}}




  • 一个线程协作的例子

爸爸给女儿和儿子喂水果。爸爸随机挑选橘子或者苹果,将橘子剥皮或者将苹果削皮放在盘子中,剥皮的速度比较快,而削皮的时间比较慢。女儿只吃橘子,儿子只吃苹果(当然我们假设女儿和儿子永远也吃不饱)。盘子只能装下3个水果。儿子吃得比较快,女儿吃得比较慢。

编程模拟该过程:

(PS:这里http://blog.csdn.net/he_qiao_2010/article/details/8762387有linux C 对这个例子的进程实现)

简单分析

信号量:

int accessplate = 1;     //表示访问盘子的信号量

int apple = 0;             //苹果个数

int orange = 0;             //橘子

int emptyplates = 3;        //空盘子

这个例子的C代码进程实现,见linux进程协作-一个小例子

这里用线程来模拟:

临界资源3个盘子,这里用一个字符串数组来表示:

String[]plates = new String[3];

每个进程对盘子进行访问的时候,对其加锁。

 

注:

1.如果用synchronized关键字修饰一个对象,则在程序执行的任意时刻,都只能由某一个线程去访问它,如果用synchronized关键字修饰一个方法,表示整个方法为同步方法。

2.SleepWait都可以使线程等待一定的毫秒数,但是Sleep在等待过程中不释放对象锁,而wait在等待过程中释放对象锁。

代码:

package hq.org;public class EateFruits {public static void main(String args[]) {Plates fruitPlates = new Plates();Father father = new Father(fruitPlates);Daughter daughter = new Daughter(fruitPlates);Son son = new Son(fruitPlates);Thread fThread = new Thread(father);Thread dThread = new Thread(daughter);Thread sThread = new Thread(son);fThread.start();dThread.start();sThread.start();//主线程每隔2秒打印出盘子的情况。while (true) {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}fruitPlates.printPlates();}}}class Plates {private static int numOfApple;private static int numOfOrange;private static int numOfEmptyPlates;public Plates() {numOfApple = 0;numOfOrange = 0;numOfEmptyPlates = 3;}//打印出盘子中的情况public void printPlates() {System.out.println( "plates:" + numOfApple + " apples," + numOfOrange + " oranges,"+ numOfEmptyPlates + " empty plates.");}public synchronized void eatAnApple() {while (0 == numOfApple ) {//如果没有苹果,等待随机毫秒数,然后重新检测numOfApple值try {this.wait((long) (Math.random()*100));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}numOfApple--;numOfEmptyPlates++;//拿到苹果后,唤醒其他正沉睡的线程。this.notifyAll();//吃苹果的时间try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Son Eat an Apple.");}public synchronized void eatAnOrange() {while (0 == numOfOrange ) {try {this.wait((long) (Math.random()*100));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}numOfOrange--;numOfEmptyPlates++;this.notifyAll();try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Daughter Eat an orange.");}public synchronized void addAnApple() {while (3 == numOfApple || 0 == numOfEmptyPlates) {try {this.wait((long) (Math.random()*100));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}numOfApple++;numOfEmptyPlates--;this.notifyAll();try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Father Add an Apple.");}public synchronized void addAnOrange() {while (3 == numOfOrange || 0 == numOfEmptyPlates) {try {this.wait( (long) (Math.random()*100) );} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}numOfOrange++;numOfEmptyPlates--;this.notifyAll();try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Father Add an orange.");}}class Daughter implements Runnable {private static Plates plates = null;public Daughter(Plates pl) {Daughter.plates = pl;}@Overridepublic void run() {while (true) {synchronized (plates) {plates.eatAnOrange();}}}}class Son implements Runnable {private static Plates plates = null;public Son(Plates pl) {Son.plates = pl;}@Overridepublic void run() {while (true) {synchronized (plates) {Son.plates.eatAnApple();}}}}class Father implements Runnable {private static Plates plates = null;public Father(Plates pl) {Father.plates = pl;}@Overridepublic void run() {while (true) {synchronized (plates) {// is Apple(40%)if ((int) (Math.random() * 100) % 100 + 1 > 60) {try {Thread.sleep(250);} catch (InterruptedException e) {e.printStackTrace();}Father.plates.addAnApple();}// is Orange(60%)else {try {Thread.sleep(250);} catch (InterruptedException e) {e.printStackTrace();}Father.plates.addAnOrange();}}}}}
运行结果:


原创粉丝点击