为了更进一步提高系统资源(CPU、内存、IO设备)利用率,多线程应运而生。
创建多线程
2种方式:继承Thread类重写run方法;实现Runnable接口重写run方法。
public class MyThread extends Thread {
public void run() {
//业务逻辑
}
}
public class MyRunnable implements Runnable {
public void run() {
//业务逻辑
}
}
使用t.start();调用,来真正的让一个新线程运行起来。
新线程与原来的线程(如果不加控制),是没有任何关系的,它们之间的代码逻辑没有谁先谁后之分,是随机的。
如果run方法中需要外界的参数,通常是通过在自定义类中新增实例变量,再使用构造方法传递进来。
public class MyRunnable implements Runnable {
private int id;
public MyRunnable(int id) {
this.id = id;
}
public void run() {
//业务逻辑
//这里可以使用id...
}
}
代码实现实现一个对象的创建的多线程
package k01;
public class Singleton {
private static Singleton st;
private Singleton(){}
public static Singleton getInstance() {
if (st == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
st = new Singleton();
}
return st;
}
}
方法一:继承Thread类重写run方法
package k01;
public class MyThread extends Thread {
@Override
public void run() {
//run方法中写的就是你想改造成多线程机制的那段逻辑代码就行
Singleton st = Singleton.getInstance();
System.out.println(st);
}
}
方法二:
实现Runnable接口重写run方法。
package k01;
public class MyRunnable implements Runnable {
@Override
public void run() {
//run方法中写的就是你想改造成多线程机制的那段逻辑代码就行
Singleton st = Singleton.getInstance();
System.out.println(st);
}
}
多线程测试
package day17.k01;
public class SingletonTest {
public static void test() {
//多线程 - 实现方式2 - 这种多线程写法是现在常用的
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new MyRunnable());
//t.run();//一定不要写t.run()
t.start();
}
}
public static void test2() {
//多线程 - 实现方式1 - 基本没人用了
for (int i = 0; i < 1000; i++) {
Thread t = new MyThread();
//t.run();//一定不要写t.run()
t.start();
}
}
public static void test1() {
//单线程
//假设10个人在做事
//如果第2个人要想开始,必须要等第1个人结束
//这样,整个任务完成的时间就是这10个人工作时间之和
for (int i = 0; i < 10; i++) {
Singleton st = Singleton.getInstance();
System.out.println(st);
}
//如果每个人之间的工作是相互独立的,为了提高工作效率
//我们可以使用多线程机制让他们同时开始,并发执行
//这样,整个任务完成的时间就是这10个人中用时最长的那个了
//可以大大提高工作效率
}
public static void main(String[] args) {
test();
}
}