看了这篇文章:http://www.ciaoshen.com/2016/10/28/tij4-21/ 有一些Java并发的内容,另外查了一些资料。
首先,Java中关于线程Thread最基本的事实是:
其次,关于Thread对象实例的构造,需要注意,start()方法依赖于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(); } }
原文:http://www.cnblogs.com/charlesblc/p/6097111.html