多线程编程

Class:Thread

interface:Runnerable

实现Runnerable接口比继承Thread类所具有的优势:

1)适合多个相同的程序代码的线程去处理同一个资源

2)可以避免JAVA中单继承的限制

3)增加程序的健壮性,代码可以被多个线程共享,代码和数据独立

所以,推荐实现接口

主程序:

<span style="font-size:24px;">import java.util.*;
import java.lang.*;

public class Generaldemo{
	
	public static void main(String[] args)
	{
		myThread mthread = new myThread();
		mythread2 th2 = new mythread2();
		Thread r = new Thread(th2);
		mthread.start();			//启动一个进程
		r.start();					//启动另一个进程
		for(int i=0;i<10000;i++)
		{
			System.out.println(Thread.currentThread().getName()+":"+i);
			try{
				Thread.sleep(5);
			}catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
	
}
</span>

线程1:

<span style="font-size:24px;">public class myThread extends Thread{
	
		public void run() {
			for(int i=0;i<10000;i++)
			{
				System.out.println(Thread.currentThread().getName()+":"+i);
				try{
					Thread.sleep(5);
				}catch(InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}
		
}</span>
线程2:
<span style="font-size:24px;">import java.lang.*;

public class mythread2 implements Runnable{
	public void run(){
		for(int i=0;i<10000;i++)
		{
			System.out.println(Thread.currentThread().getName()+":"+i);
			try{
				Thread.sleep(5);
			}catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}</span>

多线程的优先级设定:

package threaddemo;
class ThRun implements Runnable{
	public void run()
	{
		for(int i=0;i<5;i++)
		{
			try {
				Thread.sleep(1000);
				System.out.println(Thread.currentThread().getName()+":"+i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  //sleep->1s
			
		}
	}
}
public class mythread4 {

	public static void main(String[] args) {
		Thread t1 = new Thread(new ThRun(),"A");
		Thread t2 = new Thread(new ThRun(),"B");
		Thread t3 = new Thread(new ThRun(),"C");
		t1.setPriority(Thread.MIN_PRIORITY);
		t2.setPriority(Thread.NORM_PRIORITY);
		t3.setPriority(Thread.MAX_PRIORITY);
		t1.start();
		t2.start();
		t3.start();
	}
}
输出结果:
<img src="https://img-blog.csdn.net/20140919162841444?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTWFya19fWmVuZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
可以明显的看出C线程的优先级要高于B,B要高于A


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值