今天学习了的主要内容:
多线程的几种实现方式
如何向线程传入参数
多线程的几种实现方式:
继承Thread类之后创建这个类的实例重写run()方法
实现Runnable接口,然后实现其中run()方法
使用方法引用到一个没有返回值的方法
如何向线程传入参数:
调用线程类中的setter方法
使用线程中的构造函数
就相当于和平常的使用类中属性差不多,只不过这里的类是线程了罢了
ThreadTest01类(测试多种实现方式和传入参数):
package LessonForThread02;
class MyThread01 extends Thread
{
private String target;
public void setTarget(String target)
{
this.target = target;
}
@Override
public void run()
{
int i;
for (i=0; i<10; i++)
{
try
{
Thread.sleep(200);//这个循环每循环一次就休息200ms。
//在此期间,别的线程可以称这200ms时间运行。
System.out.println("This is MyThread01 run number ->" + i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class MyThread02 implements Runnable
{
private String target;
public MyThread02(String target)
{
this.target = target;
}
@Override
public void run()
{
int i;
for (i=0; i<10; i++)
{
try
{
Thread.sleep(200);//这个循环每循环一次就休息200ms。
//在此期间,别的线程可以称这200ms时间运行。
System.out.println("This is MyThread02 run number ->" + i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class ThreadTest01
{
public static void threadTest01Print()
{
int i;
for (i=0; i<10; i++)
{
try
{
Thread.sleep(200);//这个循环每循环一次就休息200ms。
//在此期间,别的线程可以称这200ms时间运行。
System.out.println("This is threadTest01Print() run number ->" + i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//主线程
public static void main(String[] args)
{
MyThread01 mt11 = new MyThread01();
mt11.setTarget("OJJJJJJJJJJJ");
mt11.start();
//运用Runnable接口
MyThread02 mt21 = new MyThread02("OHHHHHHHHHHHHH");
Thread t1 = new Thread(mt21);
t1.start();
for (int i=0; i<10; i++)
{
try
{
Thread.sleep(400);
System.out.println("This is Main Thread run number ->" + i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
//运用Lambda表达式来实现Runnable中的run();
Thread t2 = new Thread(()->{
for (int i=0; i<10; i++)
{
try
{
Thread.sleep(200);
System.out.println("This is Lambda run number ->" + i);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
t2.start();
//方法引用的方式
Thread t3 = new Thread(ThreadTest01::threadTest01Print);
t3.start();
}
}
本篇部分文字来源于:
咕嘟咖啡杨海滨老师 — 《java编程语言高级特性》
在这里十分感谢老师能够给我带来学习的激情。
2020.10.20
可以转载我的学习日记但请注明出处,谢谢。
本文章是本人学习笔记,不进行任何商用!只为记录本人学习历程。
毕