在java中有两种方式实现线程,继承Thread类和实现Runnable接口
方法一:
一个类只要继承了Thread类,同时覆写了run()方法那么就能实现多线程。
public class ThreadDemo extends Thread{
private String name;
public ThreadDemo(String name)
{
this.name=name;
}
public void run()
{
for(int i=0;i<5;i++)
System.out.print("Thread运行:"+name+"i->"+i);
}
}
public class ThreadTest {
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo("线程A");
ThreadDemo t2=new ThreadDemo("线程B");
//线程启动jvm自动找到run()方法
t1.start();
t2.start();
}
}
方法二:
实现Runnable接口,覆写公共的run()方法
public class ThreadDemo implements Runnable{
private String name;
public ThreadDemo(String name)
{
this.name=name;
}
public void run()
{
for(int i=0;i<5;i++)
System.out.print("Thread运行:"+name+"i->"+i);
}
}
public class ThreadTest {
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo("线程A");
new Thread(t1).start();
}
}
Runable比Thread线程安全
设置线程名称:
在Thread类中可以使用setName(String name),Thread(Runnable target,String name),Thread(String name)
取出线程名称:
在Thread类中可以使用getName();
public static Thread currentThread()得到当前线程的名称
在java执行中一个java程序至少启动两个线程:main,gc两个线程。
线程的休眠:
Thread.sleep(2000)需要try……catch(){}异常为InterruptException中断异常
线程的同步和异步
1,同步代码块
synchronized(this){//同步代码块}
public class ThreadDemo implements Runnable{
int tick=5;
public void run()
{
for(int i=0;i<5;i++)
synchronized(this)
{
if(this.tick>0)
System.out.println(Thread.currentThread().getName()+"->"+tick--);
}
}
}
public class ThreadTest {
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo();
new Thread(t1,"线程A").start();
new Thread(t1,"线程B").start();
new Thread(t1,"线程C").start();
}
}
2,同步方法
public class ThreadDemo implements Runnable{
int tick=5;
public void run()
{
this.sail();
}
public synchronized void sail()
{
for(int i=0;i<5;i++)
{
if(this.tick>0)
System.out.println(Thread.currentThread().getName()+"->"+tick--);
}
}
}
public class ThreadTest {
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo();
new Thread(t1,"线程A").start();
new Thread(t1,"线程B").start();
new Thread(t1,"线程C").start();
}
}