1.创建一个线程
class myThread implements Runnable
{
public void run()
{
System.out.println("线程");
}
}
class Test
{
public static void main(String args [])
{
myThread mt=new myThread();
Thread t=new Thread(mt);
t.start();
}
}
//输出的结果就是“线程”
线程是交替运行的,为了说明这个问题,如下代码
class myThread implements Runnable
{
public void run()
{
int i=0;
int sum=0;
while(i<100)
{
sum+=i;
i++;
System.out.println("my"+i);
}
}
}
class Test
{
public static void main(String args [])
{
myThread mt=new myThread();
Thread t=new Thread(mt);
t.start();
int i=0;
int sum=0;
while(i<100)
{
sum+=i;
i++;
System.out.println("main"+i);
}
}
//这段代码的运行了结果类似这种的main1 my2 main3......交替出现
这种无规律的出现方式,其原因是这段代码中共有三个线程,主线程也就是main,我们自己的线程myThreach,还有Threach,这三个线程会抢占cpu,谁抢到谁执行,所以会无规律 的出现,为了防止这样无规律发生未知的错误,使用同步代码块来防止出错
class myThread implements Runnable
{
public void run()
{
synchronized(this)//如果t线程抢到了cpu就会把这段代码全部执行完毕,等t2在执行
{
int i=0;
int sum=0;
while(i<100)
{
sum+=i;
i++;
System.out.println("my"+i);
}
}
}
}
class Test
{
public static void main(String args [])
{
myThread mt=new myThread();
Thread t=new Thread(mt);
Thread t2=new Thread(mt);
t.start();
t2.start();
//这里的两个线程同时要用mt,在没有加上同步synchronized的时候,执行顺序是乱的,各位看客可以试试,加上之后,就会按照顺序排列
}
}
线程的范围是1-10,所谓范围是指优先级,如果设置了一个线程的优先级是10,但不意味着他一定会抢到cpu,只是概率增加了
public static void main(String args [])
{
myThread mt=new myThread();
Thread t=new Thread(mt);
Thread t2=new Thread(mt);
t.setPriority(MIN_PRIORITY);//设置线程优先级
System.out.println(t.getPriority());//1
t2.setPriority(MAX_PRIORITY);
}
//还有Thread.sleep()//线程休眠
Thread.yield();//让出cpu
Thread.currentThread();//获取抢到cpu的那个对象
Thread.currentThread().getName()//获取抢到CPU线程的名字