天天看点

多线程入门

1.创建线程

(1)第一种方式就是直接继承Thread这个类,这个类其实是实现了Runnable这个接口,只不过没有显示的声明出来,

不过你要是直接继承这个类,你需要去自己写一个run的方法,这个方法里写你的多线程逻辑。

public class CreateThreadbyExtendsTh {
    public static void main(String[] args){
        System.out.println("main Thread......");
        Thread t1 = new Thread1("TTT1");
        Thread t2 = new Thread2("TTT2");
        t1.start();t2.start();
    }
}
class Thread1 extends Thread {
    Thread1 (String str) {
        super(str);
    }
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(this.getName()+" "+i+"\t");
        }
    }
}
class Thread2 extends Thread {
    Thread2 (String str) {
        super(str);
    }
    public void run() {
        for (int i = -100; i <=-90 ; i++) {
            System.out.println(this.getName()+"aaa"+i+"\t");
        }
    }
}
      

(2)第二种方式就是你的类实现Runnable这个接口,如果你去实现了这个接口,那么意味着这个接口里的方法你也要去实现了

就是run的方法,这个run方法里你可以去写你的多线程逻辑,最后只需要把你这个实现了Runnnable这个接口的类的对象传到

Thread这个构造方法里就可以了。

public class CreateThreadbyRunnable {
    public static void main(String[] args){
        System.out.println("main thread......");
        MyTask myTask = new MyTask(10);
        Thread thread = new Thread(myTask);
        thread.start();
        for (char ch = 'a'; ch <= 'k'; ch++) {
            System.out.print(" "+ch+"       ");
        }
    }
}
class MyTask implements Runnable {
    private int n;
    public MyTask(int n){
        this.n = n;
    }

    @Override
    public void run() {
        for (int i = 0; i < n; i++) {
            System.out.print(" "+i);
        }
    }
}
      

2.值得注意的是我们还要关注sleep这个方法,这个方法是使线程休眠的方法,从而执行多个线程:

import java.text.SimpleDateFormat;
import java.util.Date;
public class TestThread3 {
    public static void main(String[] args) {
        Runner r1 = new Runner("Parameter1");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);
        Thread t3 = new Thread(r1);
        Runner r2 = new Runner("Parameter2");
        Thread t4 = new Thread(r2);
        Thread t5 = new Thread(r2);
        Thread t6 = new Thread(r2);
        Timer timer = new Timer();
        Thread t7 = new Thread(timer);
        t1.setName("t1");
        t2.setName("t2");t3.setName("t3");t4.setName("t4");
        t5.setName("t5");t6.setName("t6");t7.setName("t7");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
    }
}
class Runner implements Runnable {
    String para;
    Runner(String para){
        this.para = para;
    }

    @Override
    public void run() {
        int i = 0;
        while (i < 20){
            i++;
            System.out.print("para: "+para+" ");
            System.out.println(Thread.currentThread().getName()+"No."+i);
            try {
                Thread.sleep(100);//使线程休眠,使其它线程有得到CPU的机会
            } catch (InterruptedException e){}
        }
    }
}
class Timer implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <3 ; i++) {
            System.out.print(Thread.currentThread().getName());
            System.out.println(" "+new SimpleDateFormat("yyyy-MM-dd").format( new Date( )));
            try {
                    Thread.sleep(300);
            } catch (InterruptedException e) {}
        }
    }
}      

3.还有一个关键字wait()是使线程暂停的,而notify()是使线程恢复的,synchronized这个关键字是使线程同步的,设置了这个关键字意味着多个线程不同时访问临界资源,只能被一个线程独立的占用,其它线程阻塞。

public class Basket {
    int index = 0;
    Apple[] apples = new Apple[5];
    public synchronized void push(Apple apple) {
        while (index == apples.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        apples[index] = apple;
        index ++;
    }
    public synchronized Apple pop() {
        while (index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        index--;
        return apples[index];
    }
}
      

4.还有一个关键方法就是join()这个方法是使正在运行的线程暂停下来:

public class TestJoin {
    public static void main(String[] args) {
        MyThread2 t1 = new MyThread2("MyThread");
        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {}
            for (int i = 1; i <=5 ; i++) {
                System.out.println("i am main thread");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e){}
            }
    }
}
class  MyThread2 extends Thread {
    MyThread2(String s) {
        super(s);
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5 ; i++) {
            System.out.println("i am "+getName());
            try {
                sleep(200);
            } catch (InterruptedException e) { }
        }
    }
}
      

5.这个yield()方法是为了切换线程的切换后按优先级执行

6.综合就是生产者---消费者模式:

public class Apple {
    int id;//用id标识一个苹果
    Apple(int id) {
        this.id = id;
    }
    public String toString() {
        return  "apple : "+id;
    }
}      
public class Basket {
    int index = 0;
    Apple[] apples = new Apple[5];
    public synchronized void push(Apple apple) {
        while (index == apples.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        apples[index] = apple;
        index ++;
    }
    public synchronized Apple pop() {
        while (index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        index--;
        return apples[index];
    }
}
      
public class Consumer implements Runnable {
    Basket basket = null;
    Consumer(Basket basket) {
        this.basket = basket;
    }
    @Override
    public void run() {
        for (int i = 0; i <5 ; i++) {
            Apple apple = basket.pop();
            System.out.println(Thread.currentThread().getName()+"消费了:" + apple);
            try {
                Thread.sleep((int)(Math.random() * 300));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
      
public class Producer implements Runnable {
    Basket basket = null;
    Producer(Basket basket) {
        this.basket = basket;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Apple apple = new Apple(i);
            System.out.println(Thread.currentThread().getName()+"生产了:" + apple);
            basket.push(apple);
            try {
                Thread.sleep((int)(Math.random() * 100));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
      
public class ProducerAndConsumer {
    public static void main(String[] args) {
        Basket basket = new Basket();
        Producer p = new Producer(basket);
        Consumer c = new Consumer(basket);
        Thread t1 = new Thread(p);
        t1.setName("生产者1 ");
        t1.start();
        Thread t2 = new Thread(c);
        t2.setName("消费者1 ");
        Thread t3 = new Thread(c);
        t3.setName("消费者2 ");
        t3.start();
    }
}
      

继续阅读