//继承Thread 来创建一个线程类
class MyThread extends Thread{
@Override
public void run(){
System.out.println("run");
}
}
public class Study {
public static void main(String[] args) {
MyThread myThread=new MyThread();
myThread.run();
myThread.start();//启动线程
}
}
运行了一次java程序就是启动了一个进程,一个进程里至少会有一个线程。
main()方法所包含的线程是主线程,和MyThread类创建出来的新线程,是一个并发执行的关系
class MyThread extends Thread{
@Override
public void run(){
while (true){
System.out.println("hello thread!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Study {
public static void main(String[] args) throws InterruptedException {
MyThread myThread=new MyThread();
myThread.run();
myThread.start();//启动线程
while (true){
System.out.println("hello main!");
Thread.sleep(1000);
}
}
}
方法二:匿名内部类创建 Thread 子类对象
class MyRunnable implements Runnable{
@Override
public void run(){
while (true){
System.out.println("hello thread!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Study {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
while (true){
System.out.println("hello main!");
Thread.sleep(1000);
}
}
}
若想让多个线程都干一样的活适合使用Runnable()接口
MyRunnable myRunnable=new MyRunnable();
Thread thread1=new Thread(myRunnable);
Thread thread2=new Thread(myRunnable);
thread1.start();
thread2.start();
方法三:匿名内部类创建 Runnable 子类对象
public class Study {
public static void main(String[] args) {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello thread");
}
});
}
}
方法四:lambda 表达式创建 Runnable 子类对象
public class Study {
public static void main(String[] args) {
Thread thread=new Thread(()-> {
System.out.println("hello thread");
});
thread.start();
}
}
二.多线程优势
例子:提高效率和运行速度
public class Study {
static long COUNT=100_0000_0000L;
public static void main(String[] args) throws InterruptedException {
example();
concurrency();
}
public static void concurrency() throws InterruptedException {
long beg=System.currentTimeMillis();
Thread t1=new Thread(()->{
long a=0;
for (long i = 0; i {
long a=0;
for (long i = 0; i < COUNT; i++) {
a++;
}
});
t1.start();
t2.start();
t1.join();
t2.join();
long end=System.currentTimeMillis();
System.out.println("执行的时间间隔"+(end-beg)+"ms");
}
public static void example(){
long beg=System.currentTimeMillis();
long a=0;
for (long i = 0; i
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)