JAVA 线程

来源:互联网 发布:淘宝整点秒杀 编辑:程序博客网 时间:2024/06/06 00:56

线程

  1. Java的线程是通过java.lang.Thread类实现的
  2. JVM启动时会有一个由主方法(public static void main(){})所定义的线程。
  3. 可以创建Thread的实例来创建新的线程,但是每个线程调用Thread对象的run()方法来实现多线程操作,通过Thread的start()来启动一个线程。

例子1:实现Runnable接口,然后创建Thread类

public class TestThred1 {public static void main(String argss[]){Runner r = new Runner();Thread t = new Thread(r);t.start();for(int i=0;i<100;i++){System.out.println("Main:" + i );}}}class Runner implements Runnable{public void run(){for(int i=0;i<100;i++){System.out.println("Runner: " + i);}}}
例子2:直接继承Thread类,然后实现run方法,调用start方法。
public class TestThred2 {public static void main(String argss[]){Runner r = new Runner();r.start();for(int i=0;i<100;i++){System.out.println("Main:" + i );}}}class Runner extends Thread{public void run(){for(int i=0;i<100;i++){System.out.println("Runner: " + i);}}}
一般来说,最好的是使用实现接口的方法,因为java类只能继承一个类,通过实现Runnable接口,Runner就可以继承其他的类,这样更灵活。

线程转换的状态


线程控制的基本方法

方法功能isAlive()判断线程是否还“活”着getPriority()获得线程的优先级数值setPriority()设置线程的优先级数值Thread.sleep()将当前线程睡眠指定毫秒数join()调用某线程的该方法,将当前线程与该线程“合并”,即等待该线程的结束,再恢复当前线程的运行yield()让出CPU,当前线程进入就绪队列等待调度wati()当前线程进入对象的wait pool.notity()/notifyAll唤醒对象的wait pool中的一个/所有等待线程

Thread.sleep(1000)  //表示当前线程休眠1秒,放在main方法,就是使主线程休眠t.join();  //表示t线程合并到当前线程中去,t不在是作为单独的线程运行Thread.currentThread()  //拿到当前的线程
例如:

public class TestJoin {public static void main(String[] args) {MyThread mt = new MyThread("t");mt.start();try{mt.join();  //mt子线程加入到主线程中去,合并为一个线程,所以先打印"I am t",然后打印"I am main thread".}catch(InterruptedException e){e.printStackTrace();}for(int i=0;i<10;i++){System.out.println("I am mian thread");}}}class MyThread extends Thread{MyThread(String s){super(s);}public void run(){for(int i=0;i<10;i++){System.out.println("I am  " + getName());}try{sleep(1000);}catch(InterruptedException e){return;}}}
让一个正常的线程停止:

public class TestThread3 {public static void main(String[] args) {Runner1 r = new Runner1();Thread t = new Thread(r);t.start();for(int i=0;i<100;i++){if(i % 5== 0 & i > 0){System.out.println("in thread main i=" + i);}}System.out.println("Thread main is over");r.shutdown();  //将t线程停止}}class Runner1 implements Runnable{boolean flag = true;public void run(){int i = 0;while(flag){System.out.println("Runner1 " + i++);}}public void shutdown(){flag = false;}}

线程同步:

在java语言中,引入了对象互斥锁的概念,保证共享数据操作的完整性,每个对象都对应一个可称为“互斥锁”的标记,这个标记能够保证在任意时刻,只能有一个线程访问对象。关键字synchonized来与对象的互斥锁联系。当某个对象synchronized修饰对象时,表明该对象在任一时刻只能由一个线程访问。



synchronzied的使用方法:

synchronzied(this){   //对某个对象加锁num++;try{Thread.sleep(1);}catch(InterruptedException e){System.out.println(name + ", 你是第" + num + "个使用timeer的线程");}}public synchronzied void method(){} //对某个方法加锁
例子:

public class TestSynchronized1 implements Runnable{static int b = 100;static int a = 0;public static void main(String[] args) throws Exception{TestSynchronized1 t1 = new TestSynchronized1();Thread t = new Thread(t1);t.start();System.out.println("Thread:b" + b);t1.m3();t1.m4();}public synchronized void m1() throws Exception{Thread.sleep(3000);b = 1000;System.out.println("m1:b" + b);}public synchronized void m2() throws Exception{//Thread.sleep(1000);a= 20;System.out.println("m2:a" + a);}public   synchronized void m3() throws Exception{//Thread.sleep(1500);a = 300;System.out.println("m3:a" + a);}public synchronized void m4(){b = 400;System.out.println("m4:" + b);}public void run(){try{m1();m2();}catch(Exception e){e.printStackTrace();}}}



生产者消费者问题:

public class ProducerConsumer {public static void main(String[] args) {SyncStack ss = new SyncStack();Producer p = new Producer(ss);Consumer c = new Consumer(ss);new Thread(p).start();new Thread(c).start();}}class WoTou{int id;WoTou(int id){this.id = id;}public String toString(){return "WoTou : " + id;}}class SyncStack{int index = 0;WoTou[] arrWT = new WoTou[6];public synchronized void push(WoTou wt){while(index == arrWT.length){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}}this.notifyAll();arrWT[index] = wt;index ++;}public synchronized WoTou pop(){while(index == 0){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}}this.notify();index--;return arrWT[index];}}class Producer implements Runnable{SyncStack ss = null;Producer(SyncStack ss){this.ss = ss;}public void run(){for(int i=0;i<20;i++){WoTou wt = new WoTou(i);ss.push(wt);System.out.println("生产了:" + wt);try{Thread.sleep((int)(Math.random() * 200));}catch(InterruptedException e){e.printStackTrace();}}}}class Consumer implements Runnable{SyncStack ss = null;Consumer(SyncStack ss){this.ss = ss;}public void run(){for(int i=0;i<20;i++){WoTou wt = ss.pop();System.out.println("消费了: " + wt);try{Thread.sleep((int)(Math.random() * 1000));}catch(InterruptedException e){e.printStackTrace();}}}}
Wait和sleep的区别:

Wait时别的线程可以访问锁定对象,调用wait时必须锁定对象

Sleep时别的线程不可以访问锁定对象。

0 0