Thread方式
package graph;
/*Thread 实现线程
*
*
* */
public class demo11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
cat cat = new cat();
cat.start();
}
}
class cat extends Thread {
int times =0;
//重写run函数
public void run() {
while (true) {
//休眠一秒会是线程进入到block阻塞状态 并释放资源
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
times ++;
System.out.println("hello world!" + times);
if(times ==10) {
break;
}
}
}
}
实现Runable接口:
package graph;
/*Runnable实现线程
*
* */
public class Dog{
public static void main(String[] args) {
// TODO Auto-generated method stub
bird bd = new bird();
Thread t = new Thread(bd);
t.start();
}
}
class bird implements Runnable {
int times =0;
//重写run函数
public void run() {
while (true) {
//休眠一秒会是线程进入到block阻塞状态 并释放资源
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
times ++;
System.out.println("hello world!" + times);
if(times ==10) {
break;
}
}
}
}
两个线程同时执行:
package graph;
/*
*
*
* 两个线程同时运行的案例
* */
public class Thread_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
pig pig = new pig(20);
lion li = new lion(20);
Thread t = new Thread(pig);
Thread p = new Thread(li);
t.start();
p.start();
}
}
class pig implements Runnable{
int n=0;
int times =0;
public pig(int n) {
this.n=n;
}
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
times++;
System.out.println("我是有个线程,在输出第" + times + "helloworld!");
if (times ==n) {
break;
}
}
}
}
//算数学
class lion implements Runnable{
int n=0;
int res =0;
int times =0;
public lion(int n) {
this.n=n;
}
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res = ++times;
System.out.print("当前结果是:" + res);
if (times==n) {
System.out.print("最后结果是:" + res);
break;
}
}
}
}