「线程java例子」java简单的线程实例

博主:adminadmin 2022-11-27 03:10:07 57

本篇文章给大家谈谈线程java例子,以及java简单的线程实例对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

一个简单java多线程的示例

for(int i=0;i10;i++){

System.out.println(name+"运行,i="+i);

Thread.sleep(1)

}

for循环这样改就行了,因为输出10个数比较小,当你启动启动第二个线程时第一个线程已经运行完毕,所以两次输出都是顺序输出,要么将i设置很大很大,要么让每次打印暂停一下

java 多线程的例子

多线程实际上就是多个线程同时运行,至于那个先完成是不能确定的。

* @author Rollen-Holt 实现Runnable接口

* */

class hello implements Runnable {

 public hello() {

 }

 public hello(String name) {

     this.name = name;

 }

 public void run() {

     for (int i = 0; i 5; i++) {

         System.out.println(name + "运行     " + i);

     }

 }

 public static void main(String[] args) {

     hello h1=new hello("线程A");

     Thread demo= new Thread(h1);

     hello h2=new hello("线程B");

     Thread demo1=new Thread(h2);

     demo.start();

     demo1.start();

 }

 private String name;

}

可能运行结果:

java怎么创建一个线程

Java线程类也是一个object类,它的实例都继承自java.lang.Thread或其子类。 可以用如下方式用java中创建一个线程:

Tread thread = new Thread();

执行该线程可以调用该线程的start()方法:

thread.start();

编写线程运行时执行的代码有两种方式:一种是创建Thread子类的一个实例并重写run方法,第二种是创建类的时候实现Runnable接口。接下来我们会具体讲解这两种方法:

创建Thread的子类

创建Thread子类的一个实例并重写run方法,run方法会在调用start()方法之后被执行。例子如下:

public class MyThread extends Thread {

   public void run(){

     System.out.println("MyThread running");

   }

}

可以用如下方式创建并运行上述Thread子类

MyThread myThread = new MyThread();

myTread.start();

一旦线程启动后start方法就会立即返回,而不会等待到run方法执行完毕才返回。就好像run方法是在另外一个cpu上执行一样。当run方法执行后,将会打印出字符串MyThread running。

实现Runnable接口

第二种编写线程执行代码的方式是新建一个实现了java.lang.Runnable接口的类的实例,实例中的方法可以被线程调用。下面给出例子:

public class MyRunnable implements Runnable {

   public void run(){

    System.out.println("MyRunnable running");

   }

}

为了使线程能够执行run()方法,需要在Thread类的构造函数中传入 MyRunnable的实例对象。示例如下:

Thread thread = new Thread(new MyRunnable());

thread.start();

当线程运行时,它将会调用实现了Runnable接口的run方法。上例中将会打印出”MyRunnable running”。

在Java 中多线程的实现方法有哪些,如何使用

Java多线程的创建及启动

Java中线程的创建常见有如三种基本形式

1.继承Thread类,重写该类的run()方法。

复制代码

1 class MyThread extends Thread {

2  

3     private int i = 0;

4

5     @Override

6     public void run() {

7         for (i = 0; i 100; i++) {

8             System.out.println(Thread.currentThread().getName() + " " + i);

9         }

10     }

11 }

复制代码

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0; i 100; i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i);

6             if (i == 30) {

7                 Thread myThread1 = new MyThread();     // 创建一个新的线程  myThread1  此线程进入新建状态

8                 Thread myThread2 = new MyThread();     // 创建一个新的线程 myThread2 此线程进入新建状态

9                 myThread1.start();                     // 调用start()方法使得线程进入就绪状态

10                 myThread2.start();                     // 调用start()方法使得线程进入就绪状态

11             }

12         }

13     }

14 }

复制代码

如上所示,继承Thread类,通过重写run()方法定义了一个新的线程类MyThread,其中run()方法的方法体代表了线程需要完成的任务,称之为线程执行体。当创建此线程类对象时一个新的线程得以创建,并进入到线程新建状态。通过调用线程对象引用的start()方法,使得该线程进入到就绪状态,此时此线程并不一定会马上得以执行,这取决于CPU调度时机。

2.实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。

复制代码

1 class MyRunnable implements Runnable {

2     private int i = 0;

3

4     @Override

5     public void run() {

6         for (i = 0; i 100; i++) {

7             System.out.println(Thread.currentThread().getName() + " " + i);

8         }

9     }

10 }

复制代码

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0; i 100; i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i);

6             if (i == 30) {

7                 Runnable myRunnable = new MyRunnable(); // 创建一个Runnable实现类的对象

8                 Thread thread1 = new Thread(myRunnable); // 将myRunnable作为Thread target创建新的线程

9                 Thread thread2 = new Thread(myRunnable);

10                 thread1.start(); // 调用start()方法使得线程进入就绪状态

11                 thread2.start();

12             }

13         }

14     }

15 }

复制代码

相信以上两种创建新线程的方式大家都很熟悉了,那么Thread和Runnable之间到底是什么关系呢?我们首先来看一下下面这个例子。

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4         for (int i = 0; i 100; i++) {

5             System.out.println(Thread.currentThread().getName() + " " + i);

6             if (i == 30) {

7                 Runnable myRunnable = new MyRunnable();

8                 Thread thread = new MyThread(myRunnable);

9                 thread.start();

10             }

11         }

12     }

13 }

14

15 class MyRunnable implements Runnable {

16     private int i = 0;

17

18     @Override

19     public void run() {

20         System.out.println("in MyRunnable run");

21         for (i = 0; i 100; i++) {

22             System.out.println(Thread.currentThread().getName() + " " + i);

23         }

24     }

25 }

26

27 class MyThread extends Thread {

28

29     private int i = 0;

30  

31     public MyThread(Runnable runnable){

32         super(runnable);

33     }

34

35     @Override

36     public void run() {

37         System.out.println("in MyThread run");

38         for (i = 0; i 100; i++) {

39             System.out.println(Thread.currentThread().getName() + " " + i);

40         }

41     }

42 }

复制代码

同样的,与实现Runnable接口创建线程方式相似,不同的地方在于

1 Thread thread = new MyThread(myRunnable);

那么这种方式可以顺利创建出一个新的线程么?答案是肯定的。至于此时的线程执行体到底是MyRunnable接口中的run()方法还是MyThread类中的run()方法呢?通过输出我们知道线程执行体是MyThread类中的run()方法。其实原因很简单,因为Thread类本身也是实现了Runnable接口,而run()方法最先是在Runnable接口中定义的方法。

1 public interface Runnable {

2  

3     public abstract void run();

4  

5 }

我们看一下Thread类中对Runnable接口中run()方法的实现:

复制代码

@Override

public void run() {

if (target != null) {

target.run();

}

}

复制代码

也就是说,当执行到Thread类中的run()方法时,会首先判断target是否存在,存在则执行target中的run()方法,也就是实现了Runnable接口并重写了run()方法的类中的run()方法。但是上述给到的列子中,由于多态的存在,根本就没有执行到Thread类中的run()方法,而是直接先执行了运行时类型即MyThread类中的run()方法。

3.使用Callable和Future接口创建线程。具体是创建Callable接口的实现类,并实现clall()方法。并使用FutureTask类来包装Callable实现类的对象,且以此FutureTask对象作为Thread对象的target来创建线程。

看着好像有点复杂,直接来看一个例子就清晰了。

复制代码

1 public class ThreadTest {

2

3     public static void main(String[] args) {

4

5         CallableInteger myCallable = new MyCallable();    // 创建MyCallable对象

6         FutureTaskInteger ft = new FutureTaskInteger(myCallable); //使用FutureTask来包装MyCallable对象

7

8         for (int i = 0; i 100; i++) {

9             System.out.println(Thread.currentThread().getName() + " " + i);

10             if (i == 30) {

11                 Thread thread = new Thread(ft);   //FutureTask对象作为Thread对象的target创建新的线程

12                 thread.start();                      //线程进入到就绪状态

13             }

14         }

15

16         System.out.println("主线程for循环执行完毕..");

17      

18         try {

19             int sum = ft.get();            //取得新创建的新线程中的call()方法返回的结果

20             System.out.println("sum = " + sum);

21         } catch (InterruptedException e) {

22             e.printStackTrace();

23         } catch (ExecutionException e) {

24             e.printStackTrace();

25         }

26

27     }

28 }

29

30

31 class MyCallable implements CallableInteger {

32     private int i = 0;

33

34     // 与run()方法不同的是,call()方法具有返回值

35     @Override

36     public Integer call() {

37         int sum = 0;

38         for (; i 100; i++) {

39             System.out.println(Thread.currentThread().getName() + " " + i);

40             sum += i;

41         }

42         return sum;

43     }

44

45 }

复制代码

首先,我们发现,在实现Callable接口中,此时不再是run()方法了,而是call()方法,此call()方法作为线程执行体,同时还具有返回值!在创建新的线程时,是通过FutureTask来包装MyCallable对象,同时作为了Thread对象的target。那么看下FutureTask类的定义:

1 public class FutureTaskV implements RunnableFutureV {

2  

3     //....

4  

5 }

1 public interface RunnableFutureV extends Runnable, FutureV {

2  

3     void run();

4  

5 }

于是,我们发现FutureTask类实际上是同时实现了Runnable和Future接口,由此才使得其具有Future和Runnable双重特性。通过Runnable特性,可以作为Thread对象的target,而Future特性,使得其可以取得新创建线程中的call()方法的返回值。

执行下此程序,我们发现sum = 4950永远都是最后输出的。而“主线程for循环执行完毕..”则很可能是在子线程循环中间输出。由CPU的线程调度机制,我们知道,“主线程for循环执行完毕..”的输出时机是没有任何问题的,那么为什么sum =4950会永远最后输出呢?

原因在于通过ft.get()方法获取子线程call()方法的返回值时,当子线程此方法还未执行完毕,ft.get()方法会一直阻塞,直到call()方法执行完毕才能取到返回值。

上述主要讲解了三种常见的线程创建方式,对于线程的启动而言,都是调用线程对象的start()方法,需要特别注意的是:不能对同一线程对象两次调用start()方法。

你好,本题已解答,如果满意

请点右下角“采纳答案”。

java的多线程简单例子

package e;

public class A 

{

public static void main(String args[]) throws Exception

{

new TestThread().start();

for(int i=0;i10;i++)

{

        Thread.sleep(3000);

System.out.println("main");

}

}

}

class TestThread extends Thread

{

public void run()

{

for(int i=0;i10;i++)

{

System.out.println("Test");

}

}

}

java线程的经典代码

package threadgroup;

class ThreadDemo3 extends Thread {

private String name;

private int delay;

public ThreadDemo3(String sname, int i_delay) {

name = sname;

delay = i_delay;

}

public void run() {

try {

sleep(delay);

} catch (InterruptedException e) {

}

System.out.println("多线程测试!\n" + name + "\n" + delay);

}

}

public class testMyThread {

public static void main(String[] args) {

ThreadDemo3 th1,th2,th3;

th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));

th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));

th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));

th1.start();

th2.start();

th3.start();

}

}

package threadgroup;

public class threadDemo {

public static void main(String[] args) {

Thread t = Thread.currentThread();

t.setName("你好吗?");

System.out.println("正在进行的Thread是:" + t);

try {

for (int i = 0; i 5; i++) {

System.out.println("我不叫穆继超" + i);

Thread.sleep(3000);

}

} catch (Exception e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

}

}

package threadgroup;

public class threadDemo2 implements Runnable {

public threadDemo2() {

Thread t1 = Thread.currentThread();

t1.setName("第一个主进程");

System.out.println("正在运行" + t1);

Thread t2 = new Thread(this, "");

System.out.println("在创建一个进程");

t2.start();

try {

System.out.println("使他进入第一个睡眠状态");

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第一个进程");

}

public void run() {

try {

for (int i = 0; i 5; i++) {

System.out.println("进程" + i);

Thread.sleep(3000);

}

} catch (InterruptedException e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第二个进程");

}

public static void main(String[] args) {

new threadDemo2();

}

}

关于线程java例子和java简单的线程实例的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-27,除非注明,否则均为首码项目网原创文章,转载请注明出处。