JAVA中线程的创建一般是有两种方法
一种为继承Thread类 并实现Run()方法
另一种是实现Runnable接口
建议使用接口方式创建线程,这种方式更加灵活
Demo1:继承Thread类
public class Demo_1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Dog h =new Dog();
Cat c = new Cat();
new Thread(h).start();
new Thread(c).start();
}
}
class Cat extends Thread {
@Override
public void run() {
// TODO 自动生成的方法存根
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
super.run();
System.out.println("喵喵喵喵");
}
}
}
class Dog implements Runnable{
@Override
public void run() {
// TODO 自动生成的方法存根
int i=0;
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("汪汪汪");
}
}
}
Demo2:实现Runable接口
public class Demo_2 {
int falg = 0;
public static void main(String[] args) {
// TODO 自动生成的方法存根
Num1 num1 = new Num1();
Num2 num2 = new Num2();
Thread Num1_ = new Thread(num1);
Thread Num2_ = new Thread(num2);
Num1_.start();
Num2_.start();
}
}
class Num1 implements Runnable {
@Override
public synchronized void run() {
while (true) // TODO 自动生成的方法存根
System.out.println("Hello world");
}
}
class Num2 implements Runnable {
@Override
public synchronized void run() {
// TODO 自动生成的方法存根
while (true) {
int i = 1;
System.out.println("我是第" + i + "个Hello world");
i++;
}
}
}
Demo3:涉及线程同步需使用synchronize关键字加锁
public class Dwmo3 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
TicketWindow t1 =new TicketWindow();
TicketWindow t2 = new TicketWindow();
TicketWindow t3 =new TicketWindow();
Thread t_1= new Thread(t1);
Thread t_2= new Thread(t2);
Thread t_3= new Thread(t3);
t_1.start();
t_2.start();
t_3.start();
}
}
//售票窗口类
class TicketWindow implements Runnable{
private static int nums=2000;
private static Object a=new Object();
@Override
public void run() {
// TODO 自动生成的方法存根
while(true)
{synchronized(a){//对象锁
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if (nums>0) {
System.out.println("正在售出第"+nums+"张票"+Thread.currentThread().getName());
nums--;
}
else {break;}
}
}
}
}