首页 > 代码库 > Java并发学习

Java并发学习

看了这篇文章:http://www.ciaoshen.com/2016/10/28/tij4-21/ 有一些Java并发的内容,另外查了一些资料。

 

朴素的Thread

首先,Java中关于线程Thread最基本的事实是:

  • 除非通过Native方法将本地线程加入JVM,创建线程唯一的方法就是“创建一个Thread类的实例对象,然后调用它的start()方法。”

其次,关于Thread对象实例的构造,需要注意,start()方法依赖于run()方法:

  • 要么传递一个Runnable对象给构造器做参数。
  • 要么重写Thread自己的run()方法。

 

第一种方法是实现Runnable接口。注意,Runnable里面获取线程信息需要用 Thread.currentThread()

package com.company;


class MyRunnable implements Runnable {
    public void run() {
        try {
            Thread.sleep((long)(Math.random() % 5 * 1000 + 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Here is thread %d\n", Thread.currentThread().getId());
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        MyRunnable myRunnable = new MyRunnable();
        Thread myThread1 = new Thread(myRunnable);
        Thread myThread2 = new Thread(myRunnable);
        myThread1.start();
        myThread2.start();

        // Your Codec object will be instantiated and called as such:
        //System.out.printf("ret:%d\n", ret);

        System.out.println();

    }

}

 

第二种方法是直接继承Thread,需要多继承的,要用上一种Runnable接口的方法。

package com.company;


class MyThread extends Thread {
    public void run() {
        try {
            Thread.sleep((long)(Math.random() % 5 * 1000 + 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Here is thread %d\n", getId());
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();
        myThread1.start();
        myThread2.start();

        // Your Codec object will be instantiated and called as such:
        //System.out.printf("ret:%d\n", ret);

        System.out.println();

    }

}

 

Java并发学习