java多线程
01-多线程的引入
定义:同时对多项任务加以控制。(例如,可以边听音乐边吃饭)
02-多线程的实现
方法1继承Thread类
public class Test extends Thread
{
private String ThreadName;
private int baozi=1;
public String get()
{
return this.ThreadName;
}
public void set(String ThreadName)
{
this.ThreadName=ThreadName;
}
public Test(String ThreadName)
{
super();
this.ThreadName=ThreadName;
}
public void run ()
{
while(baozi<10)
{
System.out.println(ThreadName+"吃第"+baozi+"个包子");
baozi++;
}
}
public static void main(String[] args)
{
Test t1=new Test("张三");
Test t2=new Test("李四");
t1.start();
t2.start();
//结果,张三李四一起执行
}
}
方法2Runnable接口中的run方法
public class Test implements Runnable
{
private String ThreadName;
private int baozi=1;
public String get()
{
return this.ThreadName;
}
public void Tset(String ThreadName)
{
this.ThreadName=ThreadName;
}
public Test(String ThreadName)
{
super();
this.ThreadName=ThreadName;
}
public void run ()
{
while(baozi<10)
{
System.out.println(ThreadName+"吃第"+baozi+"个包子");
baozi++;
}
}
public static void main(String[] args)
{
Test t1=new Test("张三");
Test t2=new Test("李四");
//和上面的写法不同
//t1,t2只是实现了接口的普通类
Thread t11=new Thread(t1);
Thread t12=new Thread(t2);
t11.start();
t12.start();
//结果,张三李四一起执行
}
}
利用Thread类可以节约资源
Test t1=new Test("超级张三");
Thread t11=new Thread(t1);
Thread t12=new Thread(